org.bouncycastle.util.io.pem.PemObject Java Examples

The following examples show how to use org.bouncycastle.util.io.pem.PemObject. 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: MspValidateTest.java    From julongchain with Apache License 2.0 6 votes vote down vote up
@Test
public void skKeyTest() throws IOException, JulongChainException, NoSuchAlgorithmException, InvalidKeySpecException {

    String sk_path = MspValidateTest.class.getResource("/sk-dxtest_sk").getPath();

    File inFile = new File(sk_path);
    long fileLen = inFile.length();
    Reader reader = null;
    PemObject pemObject = null;
    reader = new FileReader(inFile);
    char[] content = new char[(int) fileLen];
    reader.read(content);
    String str = new String(content);
    StringReader stringreader = new StringReader(str);
    PemReader pem = new PemReader(stringreader);
    pemObject = pem.readPemObject();

    System.out.println(Hex.toHexString(pemObject.getContent()));
}
 
Example #2
Source File: KeyCodec.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Helper function that actually writes data to the files.
 *
 * @param basePath - base path to write key
 * @param keyPair - Key pair to write to file.
 * @param privateKeyFileName - private key file name.
 * @param publicKeyFileName - public key file name.
 * @param force - forces overwriting the keys.
 * @throws IOException - On I/O failure.
 */
private synchronized void writeKey(Path basePath, KeyPair keyPair,
    String privateKeyFileName, String publicKeyFileName, boolean force)
    throws IOException {
  checkPreconditions(basePath);

  File privateKeyFile =
      Paths.get(location.toString(), privateKeyFileName).toFile();
  File publicKeyFile =
      Paths.get(location.toString(), publicKeyFileName).toFile();
  checkKeyFile(privateKeyFile, force, publicKeyFile);

  try (PemWriter privateKeyWriter = new PemWriter(new
      FileWriterWithEncoding(privateKeyFile, DEFAULT_CHARSET))) {
    privateKeyWriter.writeObject(
        new PemObject(PRIVATE_KEY, keyPair.getPrivate().getEncoded()));
  }

  try (PemWriter publicKeyWriter = new PemWriter(new
      FileWriterWithEncoding(publicKeyFile, DEFAULT_CHARSET))) {
    publicKeyWriter.writeObject(
        new PemObject(PUBLIC_KEY, keyPair.getPublic().getEncoded()));
  }
  Files.setPosixFilePermissions(privateKeyFile.toPath(), permissionSet);
  Files.setPosixFilePermissions(publicKeyFile.toPath(), permissionSet);
}
 
Example #3
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 #4
Source File: SSLContextInitializer.java    From trufflesqueak with MIT License 6 votes vote down vote up
private static CertificateInfo readPem(final File file)
                throws IOException, GeneralSecurityException {

    Certificate certificate = null;
    PrivateKey key = null;

    try (PemReader reader = new PemReader(new FileReader(file))) {

        while (true) {
            final PemObject read = reader.readPemObject();
            if (read == null) {
                break;
            } else if (read.getType().equals(CERTIFICATE)) {
                certificate = readCertificate(read.getContent());
            } else if (read.getType().equals(PRIVATE_KEY)) {
                key = readPrivateKey(read.getContent());
            }
        }

        return new CertificateInfo(certificate, key);
    }
}
 
Example #5
Source File: KeyCodec.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Writes a given public key using the default config options.
 *
 * @param key - Key to write to file.
 * @throws IOException - On I/O failure.
 */
public void writePublicKey(PublicKey key) throws IOException {
  File publicKeyFile = Paths.get(location.toString(),
      securityConfig.getPublicKeyFileName()).toFile();

  if (Files.exists(publicKeyFile.toPath())) {
    throw new IOException("Private key already exist.");
  }

  try (PemWriter keyWriter = new PemWriter(new
      FileWriterWithEncoding(publicKeyFile, DEFAULT_CHARSET))) {
    keyWriter.writeObject(
        new PemObject(PUBLIC_KEY, key.getEncoded()));
  }
  Files.setPosixFilePermissions(publicKeyFile.toPath(), permissionSet);
}
 
Example #6
Source File: Actions.java    From xipki with Apache License 2.0 6 votes vote down vote up
protected List<X509Cert> getPeerCertificates()
    throws CertificateException, IOException {
  if (StringUtil.isNotBlank(peerCertsFile)) {
    try (PemReader pemReader = new PemReader(new FileReader(peerCertsFile))) {
      List<X509Cert> certs = new LinkedList<>();
      PemObject pemObj;
      while ((pemObj = pemReader.readPemObject()) != null) {
        if (!"CERTIFICATE".equals(pemObj.getType())) {
          continue;
        }

        certs.add(X509Util.parseCert(pemObj.getContent()));
      }
      return certs.isEmpty() ? null : certs;
    }
  } else if (StringUtil.isNotBlank(peerCertFile)) {
    X509Cert cert = X509Util.parseCert(Paths.get(peerCertFile).toFile());
    return Arrays.asList(cert);
  } else {
    return null;
  }
}
 
Example #7
Source File: RestCaClient.java    From xipki with Apache License 2.0 6 votes vote down vote up
private List<X509Certificate> httpgetCaCertchain() throws Exception {
  List<X509Certificate> certchain = new LinkedList<>();
  // Get CA certificate chain
  byte[] bytes = httpGet(caUrl + "/cacertchain", CT_PEM_FILE);
  try (PemReader pemReader =
      new PemReader(new InputStreamReader(new ByteArrayInputStream(bytes)))) {
    PemObject pemObject;
    while ((pemObject = pemReader.readPemObject()) != null) {
      if ("CERTIFICATE".contentEquals(pemObject.getType())) {
        certchain.add(SdkUtil.parseCert(pemObject.getContent()));
      }
    }
  }

  if (certchain.isEmpty()) {
    throw new Exception("could not retrieve certificates");
  }
  return certchain;
}
 
Example #8
Source File: KeyCodec.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Writes a given private key using the default config options.
 *
 * @param key - Key to write to file.
 * @throws IOException - On I/O failure.
 */
public void writePrivateKey(PrivateKey key) throws IOException {
  File privateKeyFile =
      Paths.get(location.toString(),
          securityConfig.getPrivateKeyFileName()).toFile();

  if (Files.exists(privateKeyFile.toPath())) {
    throw new IOException("Private key already exist.");
  }

  try (PemWriter privateKeyWriter = new PemWriter(new
      FileWriterWithEncoding(privateKeyFile, DEFAULT_CHARSET))) {
    privateKeyWriter.writeObject(
        new PemObject(PRIVATE_KEY, key.getEncoded()));
  }
  Files.setPosixFilePermissions(privateKeyFile.toPath(), permissionSet);
}
 
Example #9
Source File: CertificateHelper.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static List<Certificate> parseChain(final String chain) throws IOException, CertificateException {
    Preconditions.checkNotNull(chain);

    final List<Certificate> certs = new ArrayList<Certificate>();
    try(final PemReader pemReader = new PemReader(new StringReader(chain));)
    {
        final PemObject pemObject = pemReader.readPemObject();
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
        final ByteArrayInputStream bais = new ByteArrayInputStream(pemObject.getContent());

        for (final Certificate cert : certificateFactory.generateCertificates(bais)) {
            if (cert instanceof X509Certificate) {
                certs.add(cert);
            }
        }
        if (certs.isEmpty()) {
            throw new IllegalStateException("Unable to decode certificate chain");
        }
    }
    return certs;
}
 
Example #10
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 #11
Source File: CertGen.java    From snowblossom with Apache License 2.0 6 votes vote down vote up
public static ByteString pemCode(byte[] encoded, String type)
{
  try
  {
    PemObject po = new PemObject(type, encoded);

    ByteArrayOutputStream b_out = new ByteArrayOutputStream();

    PemWriter w = new PemWriter( new OutputStreamWriter(b_out));

    w.writeObject(po);
    w.flush();
    w.close();

    return ByteString.copyFrom(b_out.toByteArray());
  }
  catch(java.io.IOException e)
  {
    throw new RuntimeException(e);
  }

}
 
Example #12
Source File: PemToDerConverter.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Converts PEM encoded binaries to DER encoded equivalent
 * 
 * @param pemEncoded the PEM encoded byte array
 * @return DER encoded byte array
 */
public static byte[] convert(final byte[] pemEncoded) {
	try (ByteArrayInputStream bais = new ByteArrayInputStream(pemEncoded);
			Reader reader = new InputStreamReader(bais);
			PemReader pemReader = new PemReader(reader)) {
		PemObject pemObject = pemReader.readPemObject();
		if (pemObject == null) {
			throw new DSSException("Unable to read PEM Object");
		}
		byte[] binaries = pemObject.getContent();
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		os.write(binaries, 0, binaries.length);
		return os.toByteArray();
	} catch (IOException e) {
		throw new DSSException("Unable to convert the CRL to DER", e);
	}
}
 
Example #13
Source File: PemUtils.java    From hedera-sdk-java with Apache License 2.0 6 votes vote down vote up
public static PrivateKeyInfo readPrivateKey(Reader input, @Nullable String passphrase) throws IOException {
    final PemReader pemReader = new PemReader(input);

    PemObject readObject = null;

    for (;;) {
        PemObject nextObject = pemReader.readPemObject();

        if (nextObject == null) break;
        readObject = nextObject;

        String objType = readObject.getType();

        if (passphrase != null && !passphrase.isEmpty() && objType.equals(TYPE_ENCRYPTED_PRIVATE_KEY)) {
            return decryptPrivateKey(readObject.getContent(), passphrase);
        } else if (objType.equals(TYPE_PRIVATE_KEY)) {
            return PrivateKeyInfo.getInstance(readObject.getContent());
        }
    }

    if (readObject != null && readObject.getType().equals(TYPE_ENCRYPTED_PRIVATE_KEY)) {
        throw new BadKeyException("PEM file contained an encrypted private key but no passphrase was given");
    }

    throw new BadKeyException("PEM file did not contain a private key");
}
 
Example #14
Source File: CaHelper.java    From julongchain with Apache License 2.0 6 votes vote down vote up
public static Certificate loadCertificateSM2(String certPath) throws JulongChainException {
    File certDir = new File(certPath);
    File[] files = certDir.listFiles();
    if (!certDir.isDirectory() || files == null) {
        log.error("invalid directory for certPath " + certPath);
        return null;
    }
    for (File file : files) {
        if (!file.getName().endsWith(".pem")) {
            continue;
        }
        try {
            InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
            PemReader pemReader = new PemReader(reader);
            PemObject pemObject = pemReader.readPemObject();
            reader.close();
            byte[] certBytes = pemObject.getContent();
            return Certificate.getInstance(certBytes);
        } catch (Exception e) {
            throw new JulongChainException("An error occurred :" + e.getMessage());
        }
    }
    throw new JulongChainException("no pem file found");
}
 
Example #15
Source File: CryptoUtil.java    From julongchain with Apache License 2.0 6 votes vote down vote up
/**
 * 从pem私钥文件中获取sk
 * @return
 */
public static byte[] getPrivateKey(String filePath)throws Exception{
    File inFile = new File(filePath);
    long fileLen = inFile.length();
    Reader reader = null;
    PemObject pemObject = null;
    reader = new FileReader(inFile);
    char[] content = new char[(int) fileLen];
    reader.read(content);
    String str = new String(content);
    String privateKeyPEM = str.replace("-----BEGIN PRIVATE KEY-----\n", "")
            .replace("-----END PRIVATE KEY-----", "").replace("\n", "");
    Security.addProvider(new BouncyCastleProvider());
    KeyFactory keyf = KeyFactory.getInstance("EC");
    PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKeyPEM) );
    BCECPrivateKey priKey = (BCECPrivateKey)keyf.generatePrivate(priPKCS8);
    return priKey.getD().toByteArray();
}
 
Example #16
Source File: CryptoUtil.java    From julongchain with Apache License 2.0 6 votes vote down vote up
/**
 * 读取私钥文件
 * @param skPath
 * @return
 * @throws CspException
 * @throws IOException
 */
public static byte[] readSkFile(String skPath) throws CspException, IOException {
    InputStreamReader reader = new InputStreamReader(new FileInputStream(skPath));
    PemReader pemReader = new PemReader(reader);
    PemObject pemObject = pemReader.readPemObject();
    reader.close();
    byte[] encodedData = pemObject.getContent();
    DerValue derValue = new DerValue(new ByteArrayInputStream(encodedData));
    byte[] rawPrivateKey = null;
    if (derValue.tag != 48) {
        throw new CspException("invalid key format");
    } else {
        BigInteger version = derValue.data.getBigInteger();
        if (!version.equals(BigInteger.ZERO)) {
            throw new CspException("version mismatch: (supported: " + Debug.toHexString(BigInteger.ZERO) + ", parsed: " + Debug.toHexString(version));
        } else {
            AlgorithmId algId = AlgorithmId.parse(derValue.data.getDerValue());
            rawPrivateKey = derValue.data.getOctetString();
        }
        return rawPrivateKey;
    }
}
 
Example #17
Source File: CryptoUtil.java    From julongchain with Apache License 2.0 6 votes vote down vote up
/**
 * 加载密钥文件
 * @param filePath
 * @return
 */
public static byte[] loadKeyFile(String filePath) {

    File inFile = new File(filePath);
    long fileLen = inFile.length();
    Reader reader = null;
    PemObject pemObject = null;
    try {
        reader = new FileReader(inFile);

        char[] content = new char[(int) fileLen];
        reader.read(content);
        String str = new String(content);

        StringReader stringreader = new StringReader(str);
        PemReader pem = new PemReader(stringreader);
        pemObject = pem.readPemObject();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return pemObject.getContent();
}
 
Example #18
Source File: CryptoUtil.java    From julongchain with Apache License 2.0 6 votes vote down vote up
/**
 * 私钥文件生成
 * @param path
 * @param content
 */
public static void privateKeyFileGen(String path, byte[] content) {
    PemObject pemObject = new PemObject("PRIVATE KEY", content);
    StringWriter str = new StringWriter();
    PemWriter pemWriter = new PemWriter(str);
    try {
        pemWriter.writeObject(pemObject);
        pemWriter.close();
        str.close();
        PrintWriter pw = new PrintWriter(new FileOutputStream(path + SK));
        String publiKey = new String(str.toString());
        pw.print(publiKey);
        pw.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #19
Source File: CryptoUtil.java    From julongchain with Apache License 2.0 6 votes vote down vote up
/**
 * 公钥文件生成
 * @param path
 * @param content
 */
public static void publicKeyFileGen(String path, byte[] content) {
    PemObject pemObject = new PemObject("PUBLIC KEY", content);
    StringWriter str = new StringWriter();
    PemWriter pemWriter = new PemWriter(str);
    try {
        pemWriter.writeObject(pemObject);
        pemWriter.close();
        str.close();
        PrintWriter pw = new PrintWriter(new FileOutputStream(path + PK));
        String publiKey = new String(str.toString());
        pw.print(publiKey);
        pw.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #20
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 #21
Source File: MessageStatusCli.java    From protect with MIT License 6 votes vote down vote up
private static void writeObject(final Key key, final PemWriter writer) throws IOException {

		final String description;
		if (key instanceof RSAPrivateKey) {
			description = "PAILLIER PRIVATE KEY";
		} else if (key instanceof RSAPublicKey) {
			description = "PAILLIER PUBLIC KEY";
		} else if (key instanceof ECPrivateKey) {
			description = "EC PRIVATE KEY";
		} else if (key instanceof ECPublicKey) {
			description = "EC PUBLIC KEY";
		} else if (key instanceof EdDSAPrivateKey) {
			description = "ED25519 PRIVATE KEY";
		} else if (key instanceof EdDSAPublicKey) {
			description = "ED25519 PUBLIC KEY";
		} else if (key instanceof PrivateKey) {
			description = "PRIVATE KEY";
		} else if (key instanceof PublicKey) {
			description = "PUBLIC KEY";
		} else {
			description = "KEY";
		}

		writer.writeObject(new PemObject(description, key.getEncoded()));
	}
 
Example #22
Source File: PEMImporter.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private static List<X509Certificate> readCertificateChain(File certificateChainFile)
    throws IOException, GeneralSecurityException
{
    final List<X509Certificate> certs = new ArrayList<>();
    try(final PemReader pemReader = new PemReader(Files.newBufferedReader(certificateChainFile.toPath())))
    {
        final PemObject pemObject = pemReader.readPemObject();
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
        final ByteArrayInputStream bais = new ByteArrayInputStream(pemObject.getContent());

        for (final Certificate cert : certificateFactory.generateCertificates(bais)) {
            if (cert instanceof X509Certificate) {
                certs.add((X509Certificate) cert);
            }
        }
        if (certs.isEmpty()) {
            throw new IllegalStateException("Unable to decode certificate chain");
        }
    }
    return certs;
}
 
Example #23
Source File: SecurityHelper.java    From MQTT-Essentials-A-Lightweight-IoT-Protocol with MIT License 5 votes vote down vote up
private static PrivateKey createPrivateKeyFromPemFile(final String keyFileName) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException 
{
	// Loads a privte key from the specified key file name
    final PemReader pemReader = new PemReader(new FileReader(keyFileName));
    final PemObject pemObject = pemReader.readPemObject();
    final byte[] pemContent = pemObject.getContent();
    pemReader.close();
    final PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(pemContent);
    final KeyFactory keyFactory = getKeyFactoryInstance();
    final PrivateKey privateKey = keyFactory.generatePrivate(encodedKeySpec);
    return privateKey;
}
 
Example #24
Source File: Pkcs10CsrUtils.java    From vespa with Apache License 2.0 5 votes vote down vote up
public static String toPem(Pkcs10Csr csr) {
    try (StringWriter stringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) {
        pemWriter.writeObject(new PemObject("CERTIFICATE REQUEST", csr.getBcCsr().getEncoded()));
        pemWriter.flush();
        return stringWriter.toString();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #25
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Return PrivateKey  from pem bytes.
 *
 * @param pemKey pem-encoded private key
 * @return
 */
public PrivateKey bytesToPrivateKey(byte[] pemKey) throws CryptoException {
    PrivateKey pk = null;
    CryptoException ce = null;

    try {
        PemReader pr = new PemReader(new StringReader(new String(pemKey)));
        PemObject po = pr.readPemObject();
        PEMParser pem = new PEMParser(new StringReader(new String(pemKey)));

        if (po.getType().equals("PRIVATE KEY")) {
            pk = new JcaPEMKeyConverter().getPrivateKey((PrivateKeyInfo) pem.readObject());
        } else {
            logger.trace("Found private key with type " + po.getType());
            PEMKeyPair kp = (PEMKeyPair) pem.readObject();
            pk = new JcaPEMKeyConverter().getPrivateKey(kp.getPrivateKeyInfo());
        }
    } catch (Exception e) {
        throw new CryptoException("Failed to convert private key bytes", e);
    }
    return pk;
}
 
Example #26
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * certificationRequestToPEM - Convert a PKCS10CertificationRequest to PEM
 * format.
 *
 * @param csr The Certificate to convert
 * @return An equivalent PEM format certificate.
 * @throws IOException
 */

private 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();
}
 
Example #27
Source File: BCECUtil.java    From jiguang-java-client-common with MIT License 5 votes vote down vote up
private static String convertEncodedDataToPEM(String type, byte[] encodedData) throws IOException {
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    PemWriter pWrt = new PemWriter(new OutputStreamWriter(bOut));
    try {
        PemObject pemObj = new PemObject(type, encodedData);
        pWrt.writeObject(pemObj);
    } finally {
        pWrt.close();
    }
    return new String(bOut.toByteArray());
}
 
Example #28
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
public byte[] certificateToDER(String certificatePEM) {

        byte[] content = null;

        try (PemReader pemReader = new PemReader(new StringReader(certificatePEM))) {
            final PemObject pemObject = pemReader.readPemObject();
            content = pemObject.getContent();

        } catch (IOException e) {
            // best attempt
        }

        return content;
    }
 
Example #29
Source File: IOManager.java    From acme_client with MIT License 5 votes vote down vote up
public static void writeX509CertificateChain(X509Certificate[] certificates, String path) throws IOException, CertificateEncodingException {
    try (Writer writer = new FileWriter(path); PemWriter pemWriter = new PemWriter(writer)) {
        for (X509Certificate certificate : certificates) {
            pemWriter.writeObject(new PemObject("CERTIFICATE", certificate.getEncoded()));
        }
    }
}
 
Example #30
Source File: GenerateKeyHandler.java    From webpush-java with MIT License 5 votes vote down vote up
/**
 * Write the given key to the given file.
 *
 * @param key
 * @param file
 */
private void writeKey(Key key, File file) throws IOException {
    file.createNewFile();

    try (PemWriter pemWriter = new PemWriter(new OutputStreamWriter(new FileOutputStream(file)))) {
        PemObject pemObject = new PemObject("Key", key.getEncoded());

        pemWriter.writeObject(pemObject);
    }
}