Example usage for org.bouncycastle.util.encoders Base64 encode

List of usage examples for org.bouncycastle.util.encoders Base64 encode

Introduction

In this page you can find the example usage for org.bouncycastle.util.encoders Base64 encode.

Prototype

public static byte[] encode(byte[] data) 

Source Link

Document

encode the input data producing a base 64 encoded byte array.

Usage

From source file:org.freenetproject.freemail.smtp.SMTPSessionTest.java

License:Open Source License

/**
 * Runs through a full session sending a simple message to one recipient.
 *
 * @throws IOException on IO errors with SMTP thread, should never happen
 *///  www.  j  av a2 s.  com
@Test
public void simpleSession() throws IOException {
    Assume.assumeTrue(UnitTestParameters.EXTENSIVE);

    final String message = "Date: Thu, 21 May 1998 05:33:29 -0700\r\n" + "From: "
            + TestId1Data.FreemailAccount.ADDRESS_WITH_ANGLE + "\r\n" + "Subject: Freemail SMTP test\r\n"
            + "To: " + TestId1Data.FreemailAccount.ADDRESS_WITH_ANGLE + "\r\n" + "\r\n"
            + "This is a simple SMTP test for Freemail\r\n";

    String authData = new String(
            Base64.encode(("\0" + TestId1Data.Identity.ID + "\0" + PASSWORD).getBytes("ASCII")), "ASCII");
    List<Command> commands = new LinkedList<Command>();
    commands.add(new Command(null, "220 localhost ready"));
    commands.add(new Command("EHLO", "250-localhost", "250 AUTH LOGIN PLAIN"));
    commands.add(new Command("AUTH PLAIN " + authData, "235 Authenticated"));
    commands.add(new Command("MAIL FROM:<" + TestId1Data.FreemailAccount.ADDRESS + ">", "250 OK"));
    commands.add(new Command("RCPT TO:<" + TestId1Data.FreemailAccount.ADDRESS + ">", "250 OK"));
    commands.add(new Command("DATA", "354 Go crazy"));
    commands.add(new Command(message + ".\r\n", "250 So be it"));

    runSimpleSessionTest(commands, true, Collections.singletonList(message),
            Collections.singletonList(TestId1Data.FreemailAccount.ADDRESS));
}

From source file:org.freenetproject.freemail.smtp.SMTPSessionTest.java

License:Open Source License

/**
 * Runs through a full session sending a simple message to one recipient where MessageHandler
 * returns a failure.//from  w  ww . j a v  a  2  s.  c  o  m
 *
 * @throws IOException on IO errors with SMTP thread, should never happen
 */
@Test
public void simpleSessionSendFails() throws IOException {
    Assume.assumeTrue(UnitTestParameters.EXTENSIVE);

    final String message = "Date: Thu, 21 May 1998 05:33:29 -0700\r\n" + "From: "
            + TestId1Data.FreemailAccount.ADDRESS_WITH_ANGLE + "\r\n" + "Subject: Freemail SMTP test\r\n"
            + "To: " + TestId1Data.FreemailAccount.ADDRESS_WITH_ANGLE + "\r\n" + "\r\n"
            + "This is a simple SMTP test for Freemail\r\n";

    String authData = new String(
            Base64.encode(("\0" + TestId1Data.Identity.ID + "\0" + PASSWORD).getBytes("ASCII")), "ASCII");
    List<Command> commands = new LinkedList<Command>();
    commands.add(new Command(null, "220 localhost ready"));
    commands.add(new Command("EHLO", "250-localhost", "250 AUTH LOGIN PLAIN"));
    commands.add(new Command("AUTH PLAIN " + authData, "235 Authenticated"));
    commands.add(new Command("MAIL FROM:<" + TestId1Data.FreemailAccount.ADDRESS + ">", "250 OK"));
    commands.add(new Command("RCPT TO:<" + TestId1Data.FreemailAccount.ADDRESS + ">", "250 OK"));
    commands.add(new Command("DATA", "354 Go crazy"));
    commands.add(new Command(message + ".\r\n", "452 Message sending failed"));

    runSimpleSessionTest(commands, false, Collections.singletonList(message),
            Collections.singletonList(TestId1Data.FreemailAccount.ADDRESS));
}

From source file:org.freenetproject.freemail.smtp.SMTPSessionTest.java

License:Open Source License

/**
 * Tests that the correct message is handed to the MessageHandler when the message contains
 * dot padding (see <a href="https://tools.ietf.org/html/rfc5321#section-4.5.2">RFC5321 section 4.5.2</a>).
 *
 * @throws IOException on IO errors with SMTP thread, should never happen
 *//*from   ww w .j  a  va2 s . co  m*/
@Test
public void messageWithDotPadding() throws IOException {
    Assume.assumeTrue(UnitTestParameters.EXTENSIVE);

    final String message = "Date: Thu, 21 May 1998 05:33:29 -0700\r\n" + "From: "
            + TestId1Data.FreemailAccount.ADDRESS_WITH_ANGLE + "\r\n" + "Subject: Freemail SMTP test\r\n"
            + "To: " + TestId1Data.FreemailAccount.ADDRESS_WITH_ANGLE + "\r\n" + "\r\n"
            + "This is a simple SMTP test for Freemail\r\n" + ".\r\n";
    final String padded = "Date: Thu, 21 May 1998 05:33:29 -0700\r\n" + "From: "
            + TestId1Data.FreemailAccount.ADDRESS_WITH_ANGLE + "\r\n" + "Subject: Freemail SMTP test\r\n"
            + "To: " + TestId1Data.FreemailAccount.ADDRESS_WITH_ANGLE + "\r\n" + "\r\n"
            + "This is a simple SMTP test for Freemail\r\n" + "..\r\n";

    String authData = new String(
            Base64.encode(("\0" + TestId1Data.Identity.ID + "\0" + PASSWORD).getBytes("ASCII")), "ASCII");
    List<Command> commands = new LinkedList<Command>();
    commands.add(new Command(null, "220 localhost ready"));
    commands.add(new Command("EHLO", "250-localhost", "250 AUTH LOGIN PLAIN"));
    commands.add(new Command("AUTH PLAIN " + authData, "235 Authenticated"));
    commands.add(new Command("MAIL FROM:<" + TestId1Data.FreemailAccount.ADDRESS + ">", "250 OK"));
    commands.add(new Command("RCPT TO:<" + TestId1Data.FreemailAccount.ADDRESS + ">", "250 OK"));
    commands.add(new Command("DATA", "354 Go crazy"));
    commands.add(new Command(padded + ".\r\n", "250 So be it"));

    runSimpleSessionTest(commands, true, Collections.singletonList(message),
            Collections.singletonList(TestId1Data.FreemailAccount.ADDRESS));
}

From source file:org.freenetproject.freemail.smtp.SMTPSessionTest.java

License:Open Source License

/**
 * Sends two messages in the same session to test that the state is reset properly. This checks
 * for bugs like the one fixed in 76444b878e where the state isn't cleared properly before the
 * second mail transaction starts.//from ww w  .ja va  2 s. c  o m
 *
 * @throws IOException on IO errors with SMTP thread, should never happen
 */
@Test
public void twoMessagesInOneSession() throws IOException {
    Assume.assumeTrue(UnitTestParameters.EXTENSIVE);

    final String message1 = "Date: Thu, 21 May 1998 05:33:29 -0700\r\n" + "From: "
            + TestId1Data.FreemailAccount.ADDRESS_WITH_ANGLE + "\r\n" + "Subject: Freemail SMTP test\r\n"
            + "To: " + TestId1Data.FreemailAccount.ADDRESS_WITH_ANGLE + "\r\n" + "\r\n"
            + "This is test message 1.\r\n";

    final String message2 = "Date: Thu, 21 May 1998 05:33:29 -0700\r\n" + "From: "
            + TestId1Data.FreemailAccount.ADDRESS_WITH_ANGLE + "\r\n" + "Subject: Freemail SMTP test\r\n"
            + "To: " + TestId1Data.FreemailAccount.ADDRESS_WITH_ANGLE + "\r\n" + "\r\n"
            + "This is test message 2.\r\n";

    String authData = new String(
            Base64.encode(("\0" + TestId1Data.Identity.ID + "\0" + PASSWORD).getBytes("ASCII")), "ASCII");
    List<Command> commands = new LinkedList<Command>();
    commands.add(new Command(null, "220 localhost ready"));
    commands.add(new Command("EHLO", "250-localhost", "250 AUTH LOGIN PLAIN"));
    commands.add(new Command("AUTH PLAIN " + authData, "235 Authenticated"));

    //Message 1
    commands.add(new Command("MAIL FROM:<" + TestId1Data.FreemailAccount.ADDRESS + ">", "250 OK"));
    commands.add(new Command("RCPT TO:<" + TestId1Data.FreemailAccount.ADDRESS + ">", "250 OK"));
    commands.add(new Command("DATA", "354 Go crazy"));
    commands.add(new Command(message1 + ".\r\n", "250 So be it"));

    //Message 2
    commands.add(new Command("MAIL FROM:<" + TestId1Data.FreemailAccount.ADDRESS + ">", "250 OK"));
    commands.add(new Command("RCPT TO:<" + TestId1Data.FreemailAccount.ADDRESS + ">", "250 OK"));
    commands.add(new Command("DATA", "354 Go crazy"));
    commands.add(new Command(message2 + ".\r\n", "250 So be it"));

    List<String> messages = new ArrayList<String>(2);
    messages.add(message1);
    messages.add(message2);

    List<String> recipients = new ArrayList<String>(2);
    recipients.add(TestId1Data.FreemailAccount.ADDRESS);
    recipients.add(TestId1Data.FreemailAccount.ADDRESS);

    runSimpleSessionTest(commands, true, messages, recipients);
}

From source file:org.freenetproject.freemail.smtp.SMTPStateTest.java

License:Open Source License

@Test
public void dataWithoutRcpt() throws IOException {
    final String username = BASE64_USERNAME;
    final String password = "password";
    final byte[] concatedBytes = ("\0" + username + "\0" + password).getBytes("ASCII");
    final String encoded = new String(Base64.encode(concatedBytes), "ASCII");

    List<String> commands = new LinkedList<String>();
    commands.add("AUTH PLAIN " + encoded);
    commands.add("DATA");

    List<String> expectedResponse = new LinkedList<String>();
    expectedResponse.add("220 localhost ready");
    expectedResponse.add("235 Authenticated");
    expectedResponse.add("503 RCPT first");

    runSimpleTest(commands, expectedResponse);
}

From source file:org.glite.ce.commonj.authz.gjaf.LocalUserPIP.java

License:Apache License

public void collectAttributes(Subject peerSubject, ServiceAuthorizationInterface.MessageContext context,
        QName operation) throws AuthorizationException {

    boolean missing = true;
    for (String tmps : opList) {
        missing = missing && (!tmps.equals(operation.getLocalPart()));
    }/*from w ww .j a  v  a2  s .  c o m*/
    if (missing) {
        logger.debug("Operation not enabled: " + operation.getLocalPart());
        return;
    }

    X509Certificate[] certList = (X509Certificate[]) context.getProperty(AuthZConstants.USER_CERTCHAIN_LABEL);
    if (certList == null) {
        logger.error("Cannot retrieve proxy certificate from context");
        throw new AuthorizationException("Cannot retrieve proxy certificate from context");
    }

    File tmpFile = null;
    BufferedWriter tmpFileWriter = null;
    try {
        tmpFile = File.createTempFile("userproxy", ".pem");
        tmpFileWriter = new BufferedWriter(new FileWriter(tmpFile));
        for (X509Certificate certItem : certList) {
            byte[] pemBytes = Base64.encode(certItem.getEncoded());
            tmpFileWriter.write("-----BEGIN CERTIFICATE-----");
            tmpFileWriter.newLine();
            for (int n = 0; n < pemBytes.length; n = n + 64) {
                if ((pemBytes.length - n) < 64) {
                    tmpFileWriter.write(new String(pemBytes, n, pemBytes.length - n));
                } else {
                    tmpFileWriter.write(new String(pemBytes, n, 64));
                }
                tmpFileWriter.newLine();
            }
            tmpFileWriter.write("-----END CERTIFICATE-----");
            tmpFileWriter.newLine();
            tmpFileWriter.flush();
        }
        logger.debug("Created temporary proxy " + tmpFile.getAbsolutePath());
    } catch (Throwable th) {
        if (logger.isDebugEnabled()) {
            logger.error("Cannot store proxy certificate", th);
        } else {
            logger.error("Cannot store proxy certificate: " + th.getMessage());
        }
        throw new AuthorizationException("Cannot store proxy certificate");
    } finally {
        if (tmpFileWriter != null) {
            try {
                tmpFileWriter.close();
            } catch (IOException ioEx) {
                logger.error(ioEx.getMessage());
            }
        }
    }

    int retcod = 0;
    Process chmodProc = null;
    /*
     * TODO chmod as parameter
     */
    String chmodCmd = "chmod 0600 " + tmpFile.getAbsolutePath();
    try {
        chmodProc = Runtime.getRuntime().exec(chmodCmd);
        retcod = chmodProc.waitFor();
    } catch (InterruptedException e) {
        logger.warn("Interrupted call to " + chmodCmd);
        retcod = -1;
    } catch (Exception ex) {
        if (logger.isDebugEnabled()) {
            logger.error("Cannot set permissions to the store proxy certificate", ex);

        } else {
            logger.error("Cannot set permissions to the store proxy certificate: " + ex.getMessage());
        }
        retcod = -1;
    } finally {
        if (chmodProc != null) {
            try {
                chmodProc.getInputStream().close();
            } catch (IOException e) {
                logger.error("Cannot close instream for " + chmodCmd);
            }
            try {
                chmodProc.getErrorStream().close();
            } catch (IOException e) {
                logger.error("Cannot close errstream for " + chmodCmd);
            }
            try {
                chmodProc.getOutputStream().close();
            } catch (IOException e) {
                logger.error("Cannot close outstream for " + chmodCmd);
            }
        }
    }

    if (retcod != 0)
        throw new AuthorizationException("Cannot set permissions to the store proxy certificate");

    String[] envp = new String[] { "GLEXEC_MODE=lcmaps_get_account",
            "GLEXEC_CLIENT_CERT=" + tmpFile.getAbsolutePath() };
    String[] cmdLine = new String[] { glexecPath, probeCmd };

    BufferedReader in = null;
    BufferedOutputStream out = null;
    BufferedReader err = null;
    String failureDescr = null;
    try {
        Process proc = Runtime.getRuntime().exec(cmdLine, envp);
        in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        out = new BufferedOutputStream(proc.getOutputStream());
        err = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

        proc.waitFor();
        if (proc.exitValue() != 0) {
            StringBuffer buff = new StringBuffer("glexec error: ");
            String line = err.readLine();
            while (line != null) {
                buff.append(line);
                line = err.readLine();
            }
            failureDescr = buff.toString();
            logger.error(failureDescr);
        } else {
            String tmpDN = (String) context.getProperty(AuthZConstants.USERDN_RFC2253_LABEL);
            UserInfo userInfo = parseGlexecOutput(in);
            if (userInfo.uid == null) {
                logger.warn("Cannot retrieve user ID from glexec output for: " + tmpDN);
            } else {
                logger.debug("Mapped " + tmpDN + " into " + userInfo.uid);
                context.setProperty(AuthZConstants.LOCAL_USER_ID, userInfo.uid);
            }

            if (userInfo.gid == null) {
                logger.warn("Cannot retrieve group ID from glexec output for: " + tmpDN);
            } else {
                logger.debug("Gid for " + tmpDN + ": " + userInfo.gid);
                context.setProperty(AuthZConstants.LOCAL_GROUP_ID, userInfo.gid);
            }

            if (userInfo.groups.size() > 0) {
                String[] tmpgrp = new String[userInfo.groups.size()];
                userInfo.groups.toArray(tmpgrp);
                context.setProperty(AuthZConstants.LOCAL_GROUPS_LIST, tmpgrp);
            }
        }

    } catch (Throwable th) {
        if (logger.isDebugEnabled()) {
            logger.error(th.getMessage(), th);
        } else {
            logger.error(th.getMessage());
        }
        failureDescr = th.getMessage();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioEx) {
                logger.error(ioEx.getMessage());
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException ioEx) {
                logger.error(ioEx.getMessage());
            }
        }
        if (err != null) {
            try {
                err.close();
            } catch (IOException ioEx) {
                logger.error(ioEx.getMessage());
            }
        }

        if (tmpFile != null && !tmpFile.delete()) {
            logger.error("Cannot delete file " + tmpFile.getAbsolutePath());
        }
    }

    if (failureDescr != null) {
        throw new AuthorizationException("Failed to get the local user id via glexec: " + failureDescr);
    }
}

From source file:org.glite.ce.commonj.authz.LocalUserPIP.java

License:Apache License

public void collectAttributes(Subject peerSubject, MessageContext context, QName operation)
        throws AuthorizationException {

    boolean missing = true;
    for (String tmps : opList) {
        missing = missing && (!tmps.equals(operation.getLocalPart()));
    }//from  w ww .  jav  a  2s  . c o  m
    if (missing) {
        logger.debug("Operation not enabled: " + operation.getLocalPart());
        return;
    }

    X509Certificate[] certList = (X509Certificate[]) context.getProperty(Constants.USER_CERTCHAIN_LABEL);
    if (certList == null) {
        logger.error("Cannot retrieve proxy certificate from context");
        throw new AuthorizationException("Cannot retrieve proxy certificate from context");
    }

    File tmpFile = null;
    BufferedWriter tmpFileWriter = null;
    try {
        tmpFile = File.createTempFile("userproxy", ".pem");
        tmpFileWriter = new BufferedWriter(new FileWriter(tmpFile));
        for (X509Certificate certItem : certList) {
            byte[] pemBytes = Base64.encode(certItem.getEncoded());
            tmpFileWriter.write("-----BEGIN CERTIFICATE-----");
            tmpFileWriter.newLine();
            for (int n = 0; n < pemBytes.length; n = n + 64) {
                if ((pemBytes.length - n) < 64) {
                    tmpFileWriter.write(new String(pemBytes, n, pemBytes.length - n));
                } else {
                    tmpFileWriter.write(new String(pemBytes, n, 64));
                }
                tmpFileWriter.newLine();
            }
            tmpFileWriter.write("-----END CERTIFICATE-----");
            tmpFileWriter.newLine();
            tmpFileWriter.flush();
        }
        logger.debug("Created temporary proxy " + tmpFile.getAbsolutePath());
    } catch (Throwable th) {
        logger.error("Cannot store proxy certificate", th);
        throw new AuthorizationException("Cannot store proxy certificate");
    } finally {
        if (tmpFileWriter != null) {
            try {
                tmpFileWriter.close();
            } catch (IOException ioEx) {
                logger.error(ioEx.getMessage(), ioEx);
            }
        }
    }

    int retcod = 0;
    Process chmodProc = null;
    /*
     * TODO chmod as parameter
     */
    String chmodCmd = "chmod 0600 " + tmpFile.getAbsolutePath();
    try {
        chmodProc = Runtime.getRuntime().exec(chmodCmd);
        retcod = chmodProc.waitFor();
    } catch (InterruptedException e) {
        logger.warn("Interrupted call to " + chmodCmd);
        retcod = -1;
    } catch (Exception ex) {
        logger.error("Cannot set permissions to the store proxy certificate", ex);
        retcod = -1;
    } finally {
        if (chmodProc != null) {
            try {
                chmodProc.getInputStream().close();
            } catch (IOException e) {
                logger.error("Cannot close instream for " + chmodCmd);
            }
            try {
                chmodProc.getErrorStream().close();
            } catch (IOException e) {
                logger.error("Cannot close errstream for " + chmodCmd);
            }
            try {
                chmodProc.getOutputStream().close();
            } catch (IOException e) {
                logger.error("Cannot close outstream for " + chmodCmd);
            }
        }
    }

    if (retcod != 0)
        throw new AuthorizationException("Cannot set permissions to the store proxy certificate");

    String[] envp = new String[] { "GLEXEC_MODE=lcmaps_get_account",
            "GLEXEC_CLIENT_CERT=" + tmpFile.getAbsolutePath() };
    String[] cmdLine = new String[] { glexecPath, probeCmd };

    BufferedReader in = null;
    BufferedOutputStream out = null;
    BufferedReader err = null;
    boolean needFault = false;
    try {
        Process proc = Runtime.getRuntime().exec(cmdLine, envp);
        in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        out = new BufferedOutputStream(proc.getOutputStream());
        err = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

        proc.waitFor();
        if (proc.exitValue() != 0) {
            StringBuffer buff = new StringBuffer("glexec error: ");
            String line = err.readLine();
            while (line != null) {
                buff.append(line);
                line = err.readLine();
            }
            logger.error(buff.toString());
            needFault = true;
        } else {
            String tmpDN = (String) context.getProperty(Constants.USERDN_RFC2253_LABEL);
            UserInfo userInfo = parseGlexecOutput(in);
            if (userInfo.uid == null) {
                logger.warn("Cannot retrieve user ID from glexec output for: " + tmpDN);
            } else {
                logger.debug("Mapped " + tmpDN + " into " + userInfo.uid);
                context.setProperty(Constants.LOCAL_USER_ID, userInfo.uid);
            }

            if (userInfo.gid == null) {
                logger.warn("Cannot retrieve group ID from glexec output for: " + tmpDN);
            } else {
                logger.debug("Gid for " + tmpDN + ": " + userInfo.gid);
                context.setProperty(Constants.LOCAL_GROUP_ID, userInfo.gid);
            }

            if (userInfo.groups.size() > 0) {
                String[] tmpgrp = new String[userInfo.groups.size()];
                userInfo.groups.toArray(tmpgrp);
                context.setProperty(Constants.LOCAL_GROUPS_LIST, tmpgrp);
            }
        }

    } catch (Throwable th) {
        logger.error(th.getMessage(), th);
        needFault = true;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioEx) {
                logger.error(ioEx.getMessage(), ioEx);
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException ioEx) {
                logger.error(ioEx.getMessage(), ioEx);
            }
        }
        if (err != null) {
            try {
                err.close();
            } catch (IOException ioEx) {
                logger.error(ioEx.getMessage(), ioEx);
            }
        }

        if (tmpFile != null && !tmpFile.delete()) {
            logger.error("Cannot delete file " + tmpFile.getAbsolutePath());
        }
    }

    if (needFault) {
        throw new AuthorizationException("System error reading local user information");
    }
}

From source file:org.glite.ce.commonj.utils.CEUtils.java

License:Apache License

public static String getPEM(X509Certificate[] certChain) throws CertificateEncodingException {
    if (certChain == null)
        return "";

    StringBuffer result = new StringBuffer();

    for (int k = 0; k < certChain.length; k++) {
        byte[] pemBytes = Base64.encode(certChain[k].getEncoded());

        result.append("-----BEGIN CERTIFICATE-----\n");
        for (int n = 0; n < pemBytes.length; n = n + 64) {

            if ((pemBytes.length - n) < 64) {
                result.append(new String(pemBytes, n, pemBytes.length - n));
            } else {
                result.append(new String(pemBytes, n, 64));
            }//from w  w  w  .  ja  v a2  s. c o m

            result.append("\n");
        }

        result.append("-----END CERTIFICATE-----\n");
    }

    return result.toString();
}

From source file:org.glite.security.delegation.GrDPX509Util.java

License:Apache License

/**
 * Generate a PEM encoded string of certificate from a header and a footer
 * @param bytes input stream//from www.ja va2 s  .co  m
 * @param hdr Header delimeter of certificate
 * @param ftr footer delimeter of certificate
 * @return encoded byte in pem
 * @throws IOException
* @deprecated Use org.bouncycastle.openssl.PEMWriter
 */
public static String writePEM(byte[] bytes, String hdr, String ftr) {

    StringBuffer buff = new StringBuffer();
    byte[] pemBytes = Base64.encode(bytes);
    buff.append(hdr);

    int n = 0;

    while (n < pemBytes.length) {
        if ((pemBytes.length - n) < 64) {
            buff.append(new String(pemBytes, n, pemBytes.length - n));
        } else {
            buff.append(new String(pemBytes, n, 64));
        }

        buff.append("\n");
        n = n + 64;
    }

    buff.append(ftr);

    return buff.toString();
}

From source file:org.glite.security.util.PrivateKeyReader.java

License:Apache License

/**
 * Return a PEM formatted PKCS1v2 representation of the key. The sequence
 * returned represents a full PrivateKeyInfo object. Had to re-implement as
 * the other PEM encoders produce wrong version of the key.
 * /*from w w w.j  a v a2s  .co m*/
 * @param inKey the key to encode.
 * @return a PEM format PKCS1v2 representation of the key.
 */
public static String getPEM(final PrivateKey inKey) {
    byte[] bytes = getEncoded(inKey);
    StringBuffer buffer = new StringBuffer();
    if (inKey instanceof RSAPrivateKey) {

        buffer.append("-----BEGIN RSA PRIVATE KEY-----\n");
        String keyPEM = new String(Base64.encode(bytes));

        // split the PEM data into LINE_LEN long lines.
        for (int i = 0; i < keyPEM.length(); i += LINE_LEN) {
            if (keyPEM.length() < i + LINE_LEN) {
                buffer.append(keyPEM.substring(i, keyPEM.length()));

            } else {
                buffer.append(keyPEM.substring(i, i + LINE_LEN));
            }
            buffer.append("\n");
        }
        buffer.append("-----END RSA PRIVATE KEY-----\n");
        return buffer.toString();
    }
    throw new IllegalArgumentException(
            "Trying to get PEM format string of non-RSA private key, while only RSA is supported. Class was: "
                    + inKey.getClass().getName());
}