org.bouncycastle.openssl.jcajce.JcaPEMWriter Java Examples

The following examples show how to use org.bouncycastle.openssl.jcajce.JcaPEMWriter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CertificateCodec.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the Certificate as a PEM encoded String.
 *
 * @param certificate - X.509 Certificate.
 * @return PEM Encoded Certificate String.
 * @throws SCMSecurityException - On failure to create a PEM String.
 */
public static String getPEMEncodedString(X509Certificate certificate)
    throws SCMSecurityException {
  try {
    StringWriter stringWriter = new StringWriter();
    try (JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) {
      pemWriter.writeObject(certificate);
    }
    return stringWriter.toString();
  } catch (IOException e) {
    LOG.error("Error in encoding certificate." + certificate
        .getSubjectDN().toString(), e);
    throw new SCMSecurityException("PEM Encoding failed for certificate." +
        certificate.getSubjectDN().toString(), e);
  }
}
 
Example #2
Source File: TestUtils.java    From enmasse with Apache License 2.0 6 votes vote down vote up
/**
 * Encode an X509 certificate into PEM format.
 *
 * @param certificate The certificate to encode.
 * @return the PEM encoded certificate, or {@code null} if the input was {@code null}.
 */
public static String toPem(final X509Certificate... certificates) {

    if (certificates == null) {
        return null;
    }

    final StringWriter sw = new StringWriter();

    try (JcaPEMWriter pw = new JcaPEMWriter(sw)) {
        for (X509Certificate certificate : certificates) {
            pw.writeObject(certificate);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return sw.toString();

}
 
Example #3
Source File: KeyUtils.java    From vespa with Apache License 2.0 6 votes vote down vote up
private static String toPkcs1Pem(PrivateKey privateKey) {
    try (StringWriter stringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) {
        String algorithm = privateKey.getAlgorithm();
        String type;
        if (algorithm.equals(RSA.getAlgorithmName())) {
            type = "RSA PRIVATE KEY";
        } else if (algorithm.equals(EC.getAlgorithmName())) {
            type = "EC PRIVATE KEY";
        } else {
            throw new IllegalArgumentException("Unexpected key algorithm: " + algorithm);
        }
        pemWriter.writeObject(new PemObject(type, getPkcs1Bytes(privateKey)));
        pemWriter.flush();
        return stringWriter.toString();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #4
Source File: CertificateTool.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public String convertX509CertToPem( X509Certificate x509Cert )
{
    try
    {
        StringWriter sw = new StringWriter();
        try ( JcaPEMWriter pw = new JcaPEMWriter( sw ) )
        {
            pw.writeObject( x509Cert );
        }
        return sw.toString();
    }
    catch ( IOException e )
    {
        throw new ActionFailedException( "Failed to convert certificate to PEM", e );
    }
}
 
Example #5
Source File: TLSCertificateKeyPair.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
/***
 * 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
 * @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);
}
 
Example #6
Source File: CertUtil.java    From littleca with Apache License 2.0 6 votes vote down vote up
/**
 * 不支持sm2
 *
 * @param privateKey  私钥
 * @param savePath    保存路径
 * @param password    加密保存密码
 * @param encryptType 加密类型 默认DES-EDE3-CBC
 * @throws CertException
 */
public static void savePrivateKeyPem(PrivateKey privateKey, String savePath, String password, String encryptType)
        throws CertException {
    try {
        if (null == privateKey) {
            throw new CertException("privateKey can't be null");
        }
        if (null == password) {
            throw new CertException("password can't be null");
        }
        if (null == savePath) {
            throw new CertException("savePath can't be null");
        }
        if (null == encryptType) {
            encryptType = "DES-EDE3-CBC";
        }
        JcaPEMWriter jcaPEMWriter = new JcaPEMWriter(new FileWriter(savePath));
        jcaPEMWriter.writeObject(privateKey, new JcePEMEncryptorBuilder(encryptType).build(password.toCharArray()));
        jcaPEMWriter.close();
    } catch (Exception e) {
        throw new CertException("save privateKey failed", e);
    }
}
 
Example #7
Source File: CertUtil.java    From littleca with Apache License 2.0 6 votes vote down vote up
/**
 * 明文保存 privateKey
 *
 * @param privateKey
 * @param savePath
 * @throws CertException
 */
public static void savePrivateKeyPem(final PrivateKey privateKey, String savePath) throws CertException {
    try {
        if (null == privateKey) {
            throw new CertException("privateKey can't be null");
        }
        if (null == savePath) {
            throw new CertException(" savePath can't be null");
        }
        JcaPEMWriter jcaPEMWriter = new JcaPEMWriter(new FileWriter(savePath));
        jcaPEMWriter.writeObject(privateKey);
        jcaPEMWriter.close();
    } catch (Exception e) {
        throw new CertException("save privateKey failed", e);
    }
}
 
Example #8
Source File: CertUtil.java    From littleca with Apache License 2.0 6 votes vote down vote up
/**
 * 明文保存 publicKey
 *
 * @param publicKey
 * @param savePath
 * @throws CertException
 */
public static void savePublicKeyPem(final PublicKey publicKey, String savePath) throws CertException {
    try {
        if (null == publicKey) {
            throw new CertException("publicKey can't be null");
        }
        if (null == savePath) {
            throw new CertException(" savePath can't be null");
        }
        JcaPEMWriter jcaPEMWriter = new JcaPEMWriter(new FileWriter(savePath));
        jcaPEMWriter.writeObject(publicKey);
        jcaPEMWriter.close();
    } catch (Exception e) {
        throw new CertException("save publicKey failed", e);
    }
}
 
Example #9
Source File: CertUtil.java    From littleca with Apache License 2.0 6 votes vote down vote up
/**
 * 保存公钥证书 base64编码
 *
 * @param cert
 * @param savePath
 * @throws Exception
 */
public static void saveX509CertBase64(final X509Certificate cert, String savePath) throws Exception {

    try {
        if (null == cert) {
            throw new CertException("cert can't be null");
        }
        if (null == savePath) {
            throw new CertException(" savePath can't be null");
        }
        JcaPEMWriter jcaPEMWriter = new JcaPEMWriter(new FileWriter(savePath));
        jcaPEMWriter.writeObject(cert, null);
        jcaPEMWriter.close();
    } catch (Exception e) {
        throw new CertException("save cert failed", e);
    }
}
 
Example #10
Source File: CertificateRequest.java    From jqm with Apache License 2.0 6 votes vote down vote up
public void writePemPublicToFile(String path)
{
    try
    {
        File f = new File(path);
        if (!f.getParentFile().isDirectory() && !f.getParentFile().mkdir())
        {
            throw new PkiException(
                    "couldn't create directory " + f.getParentFile().getAbsolutePath() + " for storing the SSL keystore");
        }
        try (FileWriter fw = new FileWriter(path);
             JcaPEMWriter wr = new JcaPEMWriter(fw))
        {
            wr.writeObject(holder);
            wr.flush();
        }
    }
    catch (Exception e)
    {
        throw new PkiException(e);
    }
}
 
Example #11
Source File: CertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
public static String getEncodedString(PKCS10CertificationRequest request)
    throws IOException {
  PemObject pemObject =
      new PemObject("CERTIFICATE REQUEST", request.getEncoded());
  StringWriter str = new StringWriter();
  try(JcaPEMWriter pemWriter = new JcaPEMWriter(str)) {
    pemWriter.writeObject(pemObject);
  }
  return str.toString();
}
 
Example #12
Source File: CertificateUtil.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Serialize a certificate into a PEM formatted String.
 *
 * @param certificate the certificate to be serialized.
 * @return the certificate in PEM format
 * @throws IOException thrown if the certificate cannot be converted into the PEM format.
 */
public static String serializeCertificateInPEM(final Certificate certificate) throws IOException {
  StringWriter buff = new StringWriter();
  try (JcaPEMWriter writer = new JcaPEMWriter(buff)) {
    writer.writeObject(certificate);
  }
  return buff.toString();
}
 
Example #13
Source File: PemHelper.java    From Spark with Apache License 2.0 5 votes vote down vote up
public void saveToPemFile(File file) throws FileNotFoundException, IOException {
    try (JcaPEMWriter pem = new JcaPEMWriter(new OutputStreamWriter(new FileOutputStream(file)))) {
        for (Object object : buildList) {
            pem.writeObject(object);
        }
        pem.close();
    }
}
 
Example #14
Source File: BouncyCastleSecurityProviderTool.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
/**
 * Encodes the specified security object in PEM format, using the specified encryptor. If the encryptor is null,
 * the object will not be encrypted in the generated String.
 *
 * @param object    object to encrypt (certificate, private key, etc.)
 * @param encryptor engine to encrypt the resulting PEM String, or null if no encryption should be used
 * @return a PEM-encoded String
 */
private static String encodeObjectAsPemString(Object object, PEMEncryptor encryptor) {
    StringWriter stringWriter = new StringWriter();

    try (JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) {
        pemWriter.writeObject(object, encryptor);
        pemWriter.flush();
    } catch (IOException e) {
        throw new ExportException("Unable to generate PEM string representing object", e);
    }

    return stringWriter.toString();
}
 
Example #15
Source File: CertificateSupplierModuleTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
static CertificateModule createCertificateModuleForPem(Object... objects) throws Exception {
  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  try (JcaPEMWriter pemWriter =
      new JcaPEMWriter(new OutputStreamWriter(byteArrayOutputStream, UTF_8))) {
    for (Object object : objects) {
      pemWriter.writeObject(object);
    }
  }
  return new CertificateModule(byteArrayOutputStream.toByteArray());
}
 
Example #16
Source File: Crypto.java    From athenz with Apache License 2.0 5 votes vote down vote up
public static String x509CertificatesToPEM(X509Certificate[] x509Certs) throws CryptoException {
    StringWriter sw = new StringWriter();
    try (JcaPEMWriter pw = new JcaPEMWriter(sw)) {
        for (X509Certificate x509Cert : x509Certs) {
            pw.writeObject(x509Cert);
        }
    } catch (IOException ex) {
        LOG.error("Unable to generate PEM output", ex);
        throw new CryptoException(ex);
    }
    return sw.toString();
}
 
Example #17
Source File: Crypto.java    From athenz with Apache License 2.0 5 votes vote down vote up
public static String generateX509CSR(PrivateKey privateKey, PublicKey publicKey,
                                     String x500Principal, GeneralName[] sanArray) throws OperatorCreationException, IOException {

    // Create Distinguished Name

    X500Principal subject = new X500Principal(x500Principal);

    // Create ContentSigner

    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(Crypto.RSA_SHA256);
    ContentSigner signer = csBuilder.build(privateKey);

    // Create the CSR

    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
            subject, publicKey);

    // Add SubjectAlternativeNames (SAN) if specified
    ///CLOVER:OFF
    if (sanArray != null) {
        ///CLOVER:ON
        ExtensionsGenerator extGen = new ExtensionsGenerator();
        GeneralNames subjectAltNames = new GeneralNames(sanArray);
        extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
        p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
    }

    PKCS10CertificationRequest csr = p10Builder.build(signer);

    // write to openssl PEM format

    PemObject pemObject = new PemObject("CERTIFICATE REQUEST", csr.getEncoded());
    StringWriter strWriter;
    try (JcaPEMWriter pemWriter = new JcaPEMWriter(strWriter = new StringWriter())) {
        pemWriter.writeObject(pemObject);
    }
    return strWriter.toString();
}
 
Example #18
Source File: Crypto.java    From athenz with Apache License 2.0 5 votes vote down vote up
public static String convertToPEMFormat(Object obj) {
    StringWriter writer = new StringWriter();
    try {
        try (JcaPEMWriter pemWriter = new JcaPEMWriter(writer)) {
            pemWriter.writeObject(obj);
            pemWriter.flush();
        }
        ///CLOVER:OFF
    } catch (IOException ex) {
        LOG.error("convertToPEMFormat: unable to convert object to PEM: " + ex.getMessage());
        return null;
    }
    ///CLOVER:ON
    return writer.toString();
}
 
Example #19
Source File: CertificateRequest.java    From jqm with Apache License 2.0 5 votes vote down vote up
private void generatePem()
{
    try
    {
        // PEM public key
        pemPublicFile = new ByteArrayOutputStream();

        try (Writer osw = new OutputStreamWriter(pemPublicFile);
             JcaPEMWriter wr = new  JcaPEMWriter(osw))
        {
            wr.writeObject(holder);
            wr.flush();
        }

        // PEM private key
        pemPrivateFile = new ByteArrayOutputStream();

        try (Writer osw = new OutputStreamWriter(pemPrivateFile);
             JcaPEMWriter wr = new JcaPEMWriter(osw))
        {
            wr.writeObject(privateKey);
            wr.flush();
        }
    }
    catch (Exception e)
    {
        throw new PkiException(e);
    }
}
 
Example #20
Source File: CertificateFormatter.java    From credhub with Apache License 2.0 5 votes vote down vote up
public static String pemOf(final Object pemObject) throws IOException {
  final StringWriter sw = new StringWriter();
  final JcaPEMWriter writer = new JcaPEMWriter(sw);
  writer.writeObject(pemObject);
  writer.close();
  return sw.toString();
}
 
Example #21
Source File: CertificateRequest.java    From jqm with Apache License 2.0 5 votes vote down vote up
public String writePemPrivateToString()
{
    try (StringWriter sw = new StringWriter();
         JcaPEMWriter wr = new JcaPEMWriter(sw))
    {
        wr.writeObject(privateKey);
        wr.flush();
        return sw.toString();
    }
    catch (Exception e)
    {
        throw new PkiException(e);
    }
}
 
Example #22
Source File: TlsHelper.java    From nifi with Apache License 2.0 5 votes vote down vote up
private static void outputAsPem(Object pemObj, String filename, File directory, String extension) throws IOException {
    OutputStream outputStream = new FileOutputStream(new File(directory,  TlsHelper.escapeFilename(filename) + extension));
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
    JcaPEMWriter pemWriter = new JcaPEMWriter(outputStreamWriter);
    JcaMiscPEMGenerator pemGen = new JcaMiscPEMGenerator(pemObj);
    pemWriter.writeObject(pemGen);
    pemWriter.close();
}
 
Example #23
Source File: FileHelper.java    From SAMLRaider with MIT License 5 votes vote down vote up
/**
 * Helper method for exporting PEM object.
 * 
 * @param object
 *            to export in PEM format.
 * @param filename
 *            for the file to export.
 */
public void exportPEMObject(Object pemObject, String filename) throws IOException {
	Writer writer;
	writer = new FileWriter(filename);
	JcaPEMWriter jcaPemWriter = new JcaPEMWriter(writer);
	jcaPemWriter.writeObject(pemObject);
	jcaPemWriter.flush();
	jcaPemWriter.close();
}
 
Example #24
Source File: CertificateWithPrivateKeyImpl.java    From java-certificate-authority with Apache License 2.0 5 votes vote down vote up
@Override
public String printKey() {
  final StringWriter sw = new StringWriter();
  try {
    try (JcaPEMWriter writer = new JcaPEMWriter(sw)) {
      writer.writeObject(privateKey);
      writer.flush();
      return sw.toString();
    }
  } catch (final IOException e) {
    throw new CaException(e);
  }
}
 
Example #25
Source File: CertificateWithPrivateKeyImpl.java    From java-certificate-authority with Apache License 2.0 5 votes vote down vote up
@Override
public void saveKey(File file) {
  try {
    try (BufferedWriter fw = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8,
        StandardOpenOption.CREATE)) {
      try (JcaPEMWriter writer = new JcaPEMWriter(fw)) {
        writer.writeObject(privateKey);
        writer.flush();
      }
    }
  } catch (final IOException e) {
    throw new CaException(e);
  }
}
 
Example #26
Source File: CertificateImpl.java    From java-certificate-authority with Apache License 2.0 5 votes vote down vote up
@Override
public String print() {
  final StringWriter sw = new StringWriter();
  try {
    try (JcaPEMWriter writer = new JcaPEMWriter(sw)) {
      writer.writeObject(certificate);
      writer.flush();
      return sw.toString();
    }
  } catch (final IOException e) {
    throw new CaException(e);
  }
}
 
Example #27
Source File: CertificateImpl.java    From java-certificate-authority with Apache License 2.0 5 votes vote down vote up
@Override
public void save(final File file) {
  try {
    try (BufferedWriter fw = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8,
        StandardOpenOption.CREATE)) {
      try (JcaPEMWriter writer = new JcaPEMWriter(fw)) {
        writer.writeObject(certificate);
        writer.flush();
      }
    }
  } catch (final IOException e) {
    throw new CaException(e);
  }
}
 
Example #28
Source File: CertificateRequest.java    From jqm with Apache License 2.0 5 votes vote down vote up
public void writePemPrivateToFile(String path)
{
    try (FileWriter fw = new FileWriter(path);
         JcaPEMWriter wr = new JcaPEMWriter(fw))
    {
        wr.writeObject(privateKey);
        wr.flush();
    }
    catch (Exception e)
    {
        throw new PkiException(e);
    }
}
 
Example #29
Source File: CertificateRequest.java    From jqm with Apache License 2.0 5 votes vote down vote up
public String writePemPublicToString()
{
    try (StringWriter sw = new StringWriter();
         JcaPEMWriter wr = new JcaPEMWriter(sw))
    {
        wr.writeObject(holder);
        wr.flush();
        return sw.toString();
    }
    catch (Exception e)
    {
        throw new PkiException(e);
    }
}
 
Example #30
Source File: CertUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static String x509CertificateToPem(final X509Certificate cert) throws IOException {
    final StringWriter sw = new StringWriter();
    try (final JcaPEMWriter pw = new JcaPEMWriter(sw)) {
        pw.writeObject(cert);
        pw.flush();
    }
    return sw.toString();
}