Example usage for org.bouncycastle.openssl.jcajce JcaPEMWriter writeObject

List of usage examples for org.bouncycastle.openssl.jcajce JcaPEMWriter writeObject

Introduction

In this page you can find the example usage for org.bouncycastle.openssl.jcajce JcaPEMWriter writeObject.

Prototype

public void writeObject(PemObjectGenerator obj) throws IOException 

Source Link

Usage

From source file:net.weta.components.communication.security.JavaKeystoreTest.java

License:EUPL

public static void exportCertficate(File keystore, String alias, File cert) throws Exception {
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    char[] password = "password".toCharArray();
    ks.load(new FileInputStream(keystore), password);
    java.security.cert.Certificate c = ks.getCertificate(alias);

    JcaPEMWriter writer = new JcaPEMWriter(new FileWriter(cert));
    writer.writeObject(c);
    writer.close();//ww  w  .j av  a 2 s .  c o  m
}

From source file:org.apache.zookeeper.common.X509TestHelpers.java

License:Apache License

/**
 * PEM-encodes the given private key (compatible with OpenSSL), optionally protecting it with a password, and
 * returns the result as a String./*from   w  w  w  .  ja v  a2  s .c  om*/
 * @param key the private key.
 * @param password an optional key password. If empty or null, the private key will not be encrypted.
 * @return a String containing the PEM encoding of the private key.
 * @throws IOException if converting the key to PEM format fails.
 * @throws OperatorCreationException if constructing the encryptor from the given password fails.
 */
public static String pemEncodePrivateKey(PrivateKey key, String password)
        throws IOException, OperatorCreationException {
    StringWriter stringWriter = new StringWriter();
    JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter);
    OutputEncryptor encryptor = null;
    if (password != null && password.length() > 0) {
        encryptor = new JceOpenSSLPKCS8EncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC)
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).setRandom(PRNG)
                .setPasssword(password.toCharArray()).build();
    }
    pemWriter.writeObject(new JcaPKCS8Generator(key, encryptor));
    pemWriter.close();
    return stringWriter.toString();
}

From source file:org.apache.zookeeper.common.X509TestHelpers.java

License:Apache License

/**
 * PEM-encodes the given X509 certificate (compatible with OpenSSL) and returns the result as a String.
 * @param cert the certificate.//from  w  w w.ja v  a2s  .  c om
 * @return a String containing the PEM encoding of the certificate.
 * @throws IOException if converting the certificate to PEM format fails.
 */
public static String pemEncodeX509Certificate(X509Certificate cert) throws IOException {
    StringWriter stringWriter = new StringWriter();
    JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter);
    pemWriter.writeObject(cert);
    pemWriter.close();
    return stringWriter.toString();
}

From source file:org.cesecore.keys.util.KeyTools.java

License:Open Source License

/** @return a buffer with the public key in PEM format */
public static String getAsPem(final PublicKey publicKey) throws IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final JcaPEMWriter pemWriter = new JcaPEMWriter(new OutputStreamWriter(baos));
    pemWriter.writeObject(publicKey);
    pemWriter.close();/*from w w  w. jav a 2 s  . co  m*/
    return new String(baos.toByteArray(), "UTF8");
}

From source file:org.ejbca.ui.cli.keybind.InternalKeyBindingExportCertificateCommand.java

License:Open Source License

@Override
public CommandResult executeCommand(Integer internalKeyBindingId, ParameterContainer parameters)
        throws AuthorizationDeniedException, CertificateImportException {
    final InternalKeyBindingMgmtSessionRemote internalKeyBindingMgmtSession = EjbRemoteHelper.INSTANCE
            .getRemoteSession(InternalKeyBindingMgmtSessionRemote.class);
    final CertificateStoreSessionRemote certStoreSession = EjbRemoteHelper.INSTANCE
            .getRemoteSession(CertificateStoreSessionRemote.class);
    final String filename = parameters.get(PEM_FILE_KEY);
    try {//from w  w  w  .jav a  2  s  . com
        final InternalKeyBindingInfo info = internalKeyBindingMgmtSession.getInternalKeyBindingInfo(getAdmin(),
                internalKeyBindingId);
        if (info == null) {
            getLogger().error("Internal key binding with id " + internalKeyBindingId + " does not exist.");
            return CommandResult.FUNCTIONAL_FAILURE;
        }
        final String fp = info.getCertificateId();
        if (fp == null) {
            getLogger().error("There is no certificate bound to Internal key binding with id "
                    + internalKeyBindingId + ".");
            return CommandResult.FUNCTIONAL_FAILURE;
        }
        final Certificate cert = certStoreSession.findCertificateByFingerprint(fp);
        if (cert == null) {
            getLogger().error("Certificate with fingerprint " + fp + " does not exist.");
            return CommandResult.FUNCTIONAL_FAILURE;
        }
        JcaPEMWriter pw = new JcaPEMWriter(new FileWriter(filename));
        pw.writeObject(cert);
        pw.close();
        getLogger().info("Operation completed successfully.");
        return CommandResult.SUCCESS;
    } catch (IOException e) {
        throw new IllegalStateException(
                "Failed to write PEM format certificate to \"" + filename + "\". " + e.getMessage());
    }
}

From source file:org.elasticsearch.xpack.core.ssl.CertificateGenerateTool.java

License:Open Source License

/**
 * This method handles writing out the certificate authority cert and private key if the certificate authority was generated by
 * this invocation of the tool/*from   w  w  w  . j a  v a 2s  .c  o  m*/
 * @param outputStream the output stream to write to
 * @param pemWriter the writer for PEM objects
 * @param info the certificate authority information
 */
private static void writeCAInfoIfGenerated(ZipOutputStream outputStream, JcaPEMWriter pemWriter, CAInfo info)
        throws Exception {
    if (info.generated) {
        final String caDirName = "ca/";
        ZipEntry zipEntry = new ZipEntry(caDirName);
        assert zipEntry.isDirectory();
        outputStream.putNextEntry(zipEntry);
        outputStream.putNextEntry(new ZipEntry(caDirName + "ca.crt"));
        pemWriter.writeObject(info.caCert);
        pemWriter.flush();
        outputStream.closeEntry();
        outputStream.putNextEntry(new ZipEntry(caDirName + "ca.key"));
        if (info.password != null && info.password.length > 0) {
            try {
                PEMEncryptor encryptor = new JcePEMEncryptorBuilder("DES-EDE3-CBC").setProvider(BC_PROV)
                        .build(info.password);
                pemWriter.writeObject(info.privateKey, encryptor);
            } finally {
                // we can safely nuke the password chars now
                Arrays.fill(info.password, (char) 0);
            }
        } else {
            pemWriter.writeObject(info.privateKey);
        }
        pemWriter.flush();
        outputStream.closeEntry();
    }
}

From source file:org.hyperledger.fabric.sdk.security.certgen.TLSCertificateKeyPair.java

License:Open Source License

/***
 * Creates a TLSCertificateKeyPair out of the given {@link X509Certificate} and {@link KeyPair}
 * encoded in PEM and also in DER for the certificate
 * @param x509Cert the certificate to process
 * @param keyPair  the key pair to process
 * @return a TLSCertificateKeyPair//from w w w .j  a v  a2s . c  o  m
 * @throws IOException upon failure
 */
static TLSCertificateKeyPair fromX509CertKeyPair(X509Certificate x509Cert, KeyPair keyPair) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintWriter writer = new PrintWriter(baos);
    JcaPEMWriter w = new JcaPEMWriter(writer);
    w.writeObject(x509Cert);
    w.flush();
    w.close();
    byte[] pemBytes = baos.toByteArray();

    InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(pemBytes));
    PemReader pr = new PemReader(isr);
    PemObject pem = pr.readPemObject();
    byte[] derBytes = pem.getContent();

    baos = new ByteArrayOutputStream();
    PrintWriter wr = new PrintWriter(baos);
    wr.println("-----BEGIN PRIVATE KEY-----");
    wr.println(new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded())));
    wr.println("-----END PRIVATE KEY-----");
    wr.flush();
    wr.close();
    byte[] keyBytes = baos.toByteArray();
    return new TLSCertificateKeyPair(pemBytes, derBytes, keyBytes);
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

License:Open Source License

/**
 * certificationRequestToPEM - Convert a PKCS10CertificationRequest to PEM
 * format./*from  w  w w.  j a va2s  .  c  om*/
 *
 * @param csr The Certificate to convert
 * @return An equivalent PEM format certificate.
 * @throws IOException
 */

public String certificationRequestToPEM(PKCS10CertificationRequest csr) throws IOException {
    PemObject pemCSR = new PemObject("CERTIFICATE REQUEST", csr.getEncoded());

    StringWriter str = new StringWriter();
    JcaPEMWriter pemWriter = new JcaPEMWriter(str);
    pemWriter.writeObject(pemCSR);
    pemWriter.close();
    str.close();
    return str.toString();
}

From source file:org.jboss.as.quickstarts.helloworld.HelloWorldServlet.java

License:Apache License

public static String getPemFromCertificate(X509Certificate certificate) {
    if (certificate != null) {
        StringWriter writer = new StringWriter();
        JcaPEMWriter pemWriter = new JcaPEMWriter(writer);
        try {/*  www.  j  a  v  a  2s  .c om*/
            pemWriter.writeObject(certificate);
            pemWriter.flush();
            pemWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String s = writer.toString();
        return removeBeginEnd(s);
    } else {
        return null;
    }
}

From source file:org.littleshoot.proxy.mitm.BouncyCastleSslEngineSource.java

License:Apache License

private void exportPem(Object cert, File exportFile) throws IOException {
    Writer sw = null;/*from w ww . ja va 2  s. c o m*/
    JcaPEMWriter pw = null;
    try {
        sw = new FileWriter(exportFile);
        pw = new JcaPEMWriter(sw);
        pw.writeObject(cert);
        pw.flush();
    } finally {
        IOUtils.closeQuietly(pw);
        IOUtils.closeQuietly(sw);
    }
}