org.bouncycastle.openssl.PEMParser Java Examples

The following examples show how to use org.bouncycastle.openssl.PEMParser. 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: CertUtil.java    From littleca with Apache License 2.0 7 votes vote down vote up
/**
 * 密文pem格式私钥读取
 *
 * @param privateKeyPemPath
 * @param password
 * @return
 * @throws Exception
 */
public static PrivateKey readPrivateKeyPem(String privateKeyPemPath, String password) throws CertException {
    try {
        if (null == password) {
            throw new CertException("password can't be null ");
        }
        PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(privateKeyPemPath)));
        Object readObject = pemParser.readObject();
        if (readObject instanceof PEMEncryptedKeyPair) {
            PEMEncryptedKeyPair keyPair = (PEMEncryptedKeyPair) readObject;
            PEMDecryptorProvider keyDecryptorProvider = new BcPEMDecryptorProvider(password.toCharArray());
            PEMKeyPair decryptKeyPair = keyPair.decryptKeyPair(keyDecryptorProvider);
            return new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                    .getKeyPair(decryptKeyPair).getPrivate();
        }
        throw new CertException("read privateKey failed");
    } catch (Exception e) {
        throw new CertException("read privateKey failed", e);
    }
}
 
Example #2
Source File: OcspServerExample.java    From netty-4.1.22 with Apache License 2.0 7 votes vote down vote up
private static X509Certificate[] parseCertificates(Reader reader) throws Exception {

        JcaX509CertificateConverter converter = new JcaX509CertificateConverter()
                .setProvider(new BouncyCastleProvider());

        List<X509Certificate> dst = new ArrayList<X509Certificate>();

        PEMParser parser = new PEMParser(reader);
        try {
          X509CertificateHolder holder = null;

          while ((holder = (X509CertificateHolder) parser.readObject()) != null) {
            X509Certificate certificate = converter.getCertificate(holder);
            if (certificate == null) {
              continue;
            }

            dst.add(certificate);
          }
        } finally {
            parser.close();
        }

        return dst.toArray(new X509Certificate[0]);
    }
 
Example #3
Source File: TlsHelper.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the parsed {@link KeyPair} from the provided {@link Reader}. The incoming format can be PKCS #8 or PKCS #1.
 *
 * @param pemKeyPairReader a reader with access to the serialized key pair
 * @return the key pair
 * @throws IOException if there is an error reading the key pair
 */
public static KeyPair parseKeyPairFromReader(Reader pemKeyPairReader) throws IOException {
    // Instantiate PEMParser from Reader
    try (PEMParser pemParser = new PEMParser(pemKeyPairReader)) {
        // Read the object (deserialize)
        Object parsedObject = pemParser.readObject();

        // If this is an ASN.1 private key, it's in PKCS #8 format and wraps the actual RSA private key
        if (PrivateKeyInfo.class.isInstance(parsedObject)) {
            if (isVerbose()) {
                logger.info("Provided private key is in PKCS #8 format");
            }
            PEMKeyPair keyPair = convertPrivateKeyFromPKCS8ToPKCS1((PrivateKeyInfo) parsedObject);
            return getKeyPair(keyPair);
        } else if (PEMKeyPair.class.isInstance(parsedObject)) {
            // Already in PKCS #1 format
            return getKeyPair((PEMKeyPair)parsedObject);
        } else {
            logger.warn("Expected one of %s or %s but got %s", PrivateKeyInfo.class, PEMKeyPair.class, parsedObject.getClass());
            throw new IOException("Expected private key in PKCS #1 or PKCS #8 unencrypted format");
        }
    }
}
 
Example #4
Source File: EntPayServiceImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
private String encryptRSA(File publicKeyFile, String srcString) throws WxPayException {
  try {
    Security.addProvider(new BouncyCastleProvider());
    Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
    try (PEMParser reader = new PEMParser(new FileReader(publicKeyFile))) {
      final PublicKey publicKey = new JcaPEMKeyConverter().setProvider("BC")
        .getPublicKey((SubjectPublicKeyInfo) reader.readObject());

      cipher.init(Cipher.ENCRYPT_MODE, publicKey);
      byte[] encrypt = cipher.doFinal(srcString.getBytes());
      return Base64.encodeBase64String(encrypt);
    }
  } catch (Exception e) {
    throw new WxPayException("加密出错", e);
  }
}
 
Example #5
Source File: CertUtil.java    From littleca with Apache License 2.0 6 votes vote down vote up
/**
 * 读取x509 证书
 *
 * @param pemPath
 * @return
 */
public static X509Certificate readX509Cert(String savePath) throws CertException {
    try {
        if (null == savePath) {
            throw new CertException("save path can't be null");
        }
        PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(savePath)));
        Object readObject = pemParser.readObject();
        if (readObject instanceof X509CertificateHolder) {
            X509CertificateHolder holder = (X509CertificateHolder) readObject;
            return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                    .getCertificate(holder);
        }
        pemParser.close();
        throw new CertException(savePath + "file read format failed");
    } catch (Exception e) {
        throw new CertException("read x509 cert failed", e);
    }
}
 
Example #6
Source File: X509CertUtil.java    From portecle with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Load a CSR from the specified URL.
 *
 * @param url The URL to load CSR from
 * @return The CSR
 * @throws CryptoException Problem encountered while loading the CSR
 * @throws FileNotFoundException If the CSR file does not exist, is a directory rather than a regular file, or for
 *             some other reason cannot be opened for reading
 * @throws IOException An I/O error occurred
 */
public static PKCS10CertificationRequest loadCSR(URL url)
    throws CryptoException, IOException
{
	// TODO: handle DER encoded requests too?
	try (PEMParser pr = new PEMParser(new InputStreamReader(NetUtil.openGetStream(url))))
	{
		PKCS10CertificationRequest csr = (PKCS10CertificationRequest) pr.readObject();
		ContentVerifierProvider prov = new JcaContentVerifierProviderBuilder().build(csr.getSubjectPublicKeyInfo());

		if (!csr.isSignatureValid(prov))
		{
			throw new CryptoException(RB.getString("NoVerifyCsr.exception.message"));
		}

		return csr;
	}
	catch (ClassCastException | OperatorCreationException | PKCSException ex)
	{
		throw new CryptoException(RB.getString("NoLoadCsr.exception.message"), ex);
	}
}
 
Example #7
Source File: KeyReader.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
public PKCS8EncodedKeySpec readPrivateKey(FileInputStream fis, Optional<String> keyPassword)
        throws IOException {
    PEMParser keyReader = new PEMParser(new InputStreamReader(fis));

    PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder().build(keyPassword.get().toCharArray());

    Object keyPair = keyReader.readObject();
    keyReader.close();

    PrivateKeyInfo keyInfo;

    if (keyPair instanceof PEMEncryptedKeyPair) {
        PEMKeyPair decryptedKeyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptorProvider);
        keyInfo = decryptedKeyPair.getPrivateKeyInfo();
    } else {
        keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
    }

    return new PKCS8EncodedKeySpec(keyInfo.getEncoded());
}
 
Example #8
Source File: KeyReader.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
public PKCS8EncodedKeySpec readPrivateKey(FileInputStream fis, Optional<String> keyPassword)
        throws IOException {
    PEMParser keyReader = new PEMParser(new InputStreamReader(fis));

    PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder().build(keyPassword.get().toCharArray());

    Object keyPair = keyReader.readObject();
    keyReader.close();

    PrivateKeyInfo keyInfo;

    if (keyPair instanceof PEMEncryptedKeyPair) {
        PEMKeyPair decryptedKeyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptorProvider);
        keyInfo = decryptedKeyPair.getPrivateKeyInfo();
    } else {
        keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
    }

    return new PKCS8EncodedKeySpec(keyInfo.getEncoded());
}
 
Example #9
Source File: CertificateTool.java    From peer-os with Apache License 2.0 6 votes vote down vote up
/**
 * Convert X509 certificate in PEM format to X509Certificate object
 *
 * @param x509InPem X509 certificate in PEM format
 *
 * @return {@code X509Certificate}
 */
public X509Certificate convertX509PemToCert( String x509InPem )
{
    try
    {
        PEMParser pemParser = new PEMParser( new StringReader( x509InPem ) );
        JcaX509CertificateConverter x509CertificateConverter = new JcaX509CertificateConverter();

        Object o = pemParser.readObject();
        return x509CertificateConverter.getCertificate( ( X509CertificateHolder ) o );
    }
    catch ( Exception e )
    {
        throw new ActionFailedException( "Failed to convert PEM to certificate", e );
    }
}
 
Example #10
Source File: SSLFactory.java    From ts-reaktive with MIT License 6 votes vote down vote up
/**
 * Reads a base64-format PEM key and returns a Java PrivateKey for it.
 * @param privateKey PEM-encoded private key
 */
public static PrivateKey readPrivateKey(String privateKey) {
    try (StringReader keyReader = new StringReader(privateKey);
         PEMParser pemReader = new PEMParser(keyReader)) {
        
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        Object keyPair = pemReader.readObject();
        if (keyPair instanceof PrivateKeyInfo) {
            return converter.getPrivateKey((PrivateKeyInfo) keyPair);
        } else {
            return converter.getPrivateKey(((PEMKeyPair) keyPair).getPrivateKeyInfo());
        }
    } catch (IOException x) {
        // Shouldn't occur, since we're only reading from strings
        throw new RuntimeException(x);            
    }
}
 
Example #11
Source File: BasicKeyStore.java    From env-keystore with MIT License 6 votes vote down vote up
protected static java.security.KeyStore createKeyStore(final Reader keyReader, final Reader certReader, final String password)
    throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
  PrivateKey key = getPrivateKeyFromPEM(keyReader);
  keyReader.close();

  PEMParser parser = new PEMParser(certReader);
  java.security.KeyStore ks = java.security.KeyStore.getInstance(DEFAULT_TYPE);
  ks.load(null);

  List<X509Certificate> certificates = new ArrayList<>();

  X509Certificate certificate;
  while ((certificate = parseCert(parser)) != null) {
    certificates.add(certificate);
  }

  ks.setKeyEntry("alias", key, password.toCharArray(), certificates.toArray(new X509Certificate[]{}));

  parser.close();
  return ks;
}
 
Example #12
Source File: BasicKeyStore.java    From env-keystore with MIT License 6 votes vote down vote up
protected static PrivateKey getPrivateKeyFromPEM(final Reader keyReader)
    throws IOException {
  final JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter();

  final PEMParser pem = new PEMParser(keyReader);

  PrivateKey key;
  Object pemContent = pem.readObject();
  if (pemContent instanceof PEMKeyPair) {
    PEMKeyPair pemKeyPair = (PEMKeyPair) pemContent;
    KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);
    key = keyPair.getPrivate();
  } else if (pemContent instanceof PrivateKeyInfo) {
    PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemContent;
    key = jcaPEMKeyConverter.getPrivateKey(privateKeyInfo);
  } else {
    throw new IllegalArgumentException("Unsupported private key format '" + pemContent.getClass().getSimpleName() + '"');
  }

  pem.close();
  return key;
}
 
Example #13
Source File: OcspHandler.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public OcspHandler(String responderCertPath, String responderKeyPath)
        throws OperatorCreationException, GeneralSecurityException, IOException {
    final Certificate certificate = CertificateFactory.getInstance("X509")
            .generateCertificate(X509OCSPResponderTest.class.getResourceAsStream(responderCertPath));

    chain = new X509CertificateHolder[] {new X509CertificateHolder(certificate.getEncoded())};

    final AsymmetricKeyParameter publicKey = PublicKeyFactory.createKey(certificate.getPublicKey().getEncoded());

    subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(publicKey);

    final InputStream keyPairStream = X509OCSPResponderTest.class.getResourceAsStream(responderKeyPath);

    try (final PEMParser keyPairReader = new PEMParser(new InputStreamReader(keyPairStream))) {
        final PEMKeyPair keyPairPem = (PEMKeyPair) keyPairReader.readObject();
        privateKey = PrivateKeyFactory.createKey(keyPairPem.getPrivateKeyInfo());
    }
}
 
Example #14
Source File: Crypto.java    From athenz with Apache License 2.0 6 votes vote down vote up
public static PKCS10CertificationRequest getPKCS10CertRequest(String csr) {

        if (csr == null || csr.isEmpty()) {
            LOG.error("getPKCS10CertRequest: CSR is null or empty");
            throw new CryptoException("CSR is null or empty");
        }

        try {
            Reader csrReader = new StringReader(csr);
            try (PEMParser pemParser = new PEMParser(csrReader)) {
                Object pemObj = pemParser.readObject();
                ///CLOVER:OFF
                if (pemObj instanceof PKCS10CertificationRequest) {
                    return (PKCS10CertificationRequest) pemObj;
                }
                ///CLOVER:ON
            }
        } catch (IOException ex) {
            LOG.error("getPKCS10CertRequest: unable to parse csr: " + ex.getMessage());
            throw new CryptoException(ex);
        }
        ///CLOVER:OFF
        return null;
        ///CLOVER:ON
    }
 
Example #15
Source File: PrivateKeyProvider.java    From XS2A-Sandbox with Apache License 2.0 6 votes vote down vote up
/**
 * Load private key from classpath.
 *
 * @param filename Name of the key file. Suffix should be .key
 * @return PrivateKey
 */
public PrivateKey getKeyFromClassPath(String filename) {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    InputStream stream = loader.getResourceAsStream("certificates/" + filename);
    if (stream == null) {
        throw new CertificateException("Could not read private key from classpath:" + "certificates/" + filename);
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    try {
        Security.addProvider(new BouncyCastleProvider());
        PEMParser pp = new PEMParser(br);
        PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
        KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
        pp.close();
        return kp.getPrivate();
    } catch (IOException ex) {
        throw new CertificateException("Could not read private key from classpath", ex);
    }
}
 
Example #16
Source File: CertificateUtils.java    From docker-java with Apache License 2.0 6 votes vote down vote up
/**
 * "ca.pem" from Reader
 */
public static KeyStore createTrustStore(final Reader certReader) throws IOException, CertificateException,
        KeyStoreException, NoSuchAlgorithmException {
    try (PEMParser pemParser = new PEMParser(certReader)) {

        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(null);

        int index = 1;
        Object pemCert;

        while ((pemCert = pemParser.readObject()) != null) {
            Certificate caCertificate = new JcaX509CertificateConverter()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                    .getCertificate((X509CertificateHolder) pemCert);
            trustStore.setCertificateEntry("ca-" + index, caCertificate);
            index++;
        }

        return trustStore;
    }
}
 
Example #17
Source File: CertificateUtils.java    From docker-java with Apache License 2.0 6 votes vote down vote up
/**
 * Return private key ("key.pem") from Reader
 */
@CheckForNull
public static PrivateKey loadPrivateKey(final Reader reader) throws IOException, NoSuchAlgorithmException,
        InvalidKeySpecException {
    try (PEMParser pemParser = new PEMParser(reader)) {
        Object readObject = pemParser.readObject();
        while (readObject != null) {
            PrivateKeyInfo privateKeyInfo = getPrivateKeyInfoOrNull(readObject);
            if (privateKeyInfo != null) {
                return new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
            }
            readObject = pemParser.readObject();
        }
    }

    return null;
}
 
Example #18
Source File: CertificateUtils.java    From docker-java with Apache License 2.0 6 votes vote down vote up
/**
 * "cert.pem" from reader
 */
public static List<Certificate> loadCertificates(final Reader reader) throws IOException,
        CertificateException {
    try (PEMParser pemParser = new PEMParser(reader)) {
        List<Certificate> certificates = new ArrayList<>();

        JcaX509CertificateConverter certificateConverter = new JcaX509CertificateConverter()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME);
        Object certObj;

        while ((certObj = pemParser.readObject()) != null) {
            if (certObj instanceof X509CertificateHolder) {
                X509CertificateHolder certificateHolder = (X509CertificateHolder) certObj;
                certificates.add(certificateConverter.getCertificate(certificateHolder));
            }
        }

        return certificates;
    }
}
 
Example #19
Source File: DockerCertificates.java    From docker-client with Apache License 2.0 6 votes vote down vote up
private PrivateKey readPrivateKey(final Path file)
    throws IOException, InvalidKeySpecException, DockerCertificateException {
  try (final BufferedReader reader = Files.newBufferedReader(file, Charset.defaultCharset());
       final PEMParser pemParser = new PEMParser(reader)) {

    final Object readObject = pemParser.readObject();

    if (readObject instanceof PEMKeyPair) {
      final PEMKeyPair clientKeyPair = (PEMKeyPair) readObject;
      return generatePrivateKey(clientKeyPair.getPrivateKeyInfo());
    } else if (readObject instanceof PrivateKeyInfo) {
      return generatePrivateKey((PrivateKeyInfo) readObject);
    }

    throw new DockerCertificateException("Can not generate private key from file: "
        + file.toString());
  }
}
 
Example #20
Source File: CertUtils.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private static PrivateKey handleECKey(InputStream keyInputStream) throws IOException {
  // Let's wrap the code to a callable inner class to avoid NoClassDef when loading this class.
  try {
    return new Callable<PrivateKey>() {
      @Override
      public PrivateKey call() {
        try {
          if (Security.getProvider("BC") == null) {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
          }
          PEMKeyPair keys = (PEMKeyPair) new PEMParser(new InputStreamReader(keyInputStream)).readObject();
          return new
            JcaPEMKeyConverter().
            getKeyPair(keys).
            getPrivate();
        } catch (IOException exception) {
          exception.printStackTrace();
        }
        return null;
      }
    }.call();
  } catch (NoClassDefFoundError e) {
    throw new KubernetesClientException("JcaPEMKeyConverter is provided by BouncyCastle, an optional dependency. To use support for EC Keys you must explicitly add this dependency to classpath.");
  }
}
 
Example #21
Source File: DKIMSign.java    From james-project with Apache License 2.0 6 votes vote down vote up
private PrivateKey extractPrivateKey(InputStream rawKey, char[] passphrase) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    try (InputStreamReader pemReader = new InputStreamReader(rawKey)) {
        try (PEMParser pemParser = new PEMParser(pemReader)) {
            Object pemObject = pemParser.readObject();
            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
            KeyPair keyPair;
            if (pemObject instanceof PrivateKeyInfo) {
                return converter.getPrivateKey((PrivateKeyInfo)pemObject);
            }
            if (pemObject instanceof PEMEncryptedKeyPair) {
                PEMEncryptedKeyPair pemEncryptedKeyPair = (PEMEncryptedKeyPair) pemObject;
                PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase);
                keyPair = converter.getKeyPair(pemEncryptedKeyPair.decryptKeyPair(decProv));
            } else {
                keyPair = converter.getKeyPair((PEMKeyPair) pemObject);
            }

            KeyFactory keyFac = KeyFactory.getInstance("RSA");
            RSAPrivateCrtKeySpec privateKeySpec = keyFac.getKeySpec(keyPair.getPrivate(), RSAPrivateCrtKeySpec.class);

            return keyFac.generatePrivate(privateKeySpec);
        }
    }
}
 
Example #22
Source File: CsrLoaderImpl.java    From java-certificate-authority with Apache License 2.0 6 votes vote down vote up
@Override
public CSR getCsr() {
  try {
    try (Reader pemReader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
      try (final PEMParser pemParser = new PEMParser(pemReader)) {
        final Object parsedObj = pemParser.readObject();

        if (parsedObj instanceof PKCS10CertificationRequest) {
          final PKCS10CertificationRequest csr = (PKCS10CertificationRequest) parsedObj;
          return new CsrImpl(csr);
        } else
          throw new CaException("Not a PKCS10CertificationRequest");
      }
    }
  } catch (final IOException e) {
    throw new CaException(e);
  }
}
 
Example #23
Source File: JwtCreatorCallout.java    From iloveapis2015-jwt-jwe-jws with Apache License 2.0 6 votes vote down vote up
private static PrivateKey generatePrivateKey(PrivateKeyInfo info)
    throws InvalidKeySpecException, GeneralSecurityException, NoSuchAlgorithmException, IOException, PEMException
{
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    PEMParser pr = new PEMParser(new StringReader(new String(info.keyBytes, StandardCharsets.UTF_8)));
    Object o = pr.readObject();

    if (o == null || !((o instanceof PEMKeyPair) || (o instanceof PEMEncryptedKeyPair))) {
        throw new IllegalStateException("Didn't find OpenSSL key");
    }
    KeyPair kp;
    if (o instanceof PEMEncryptedKeyPair) {
        JcePEMDecryptorProviderBuilder bcDecProvider = new JcePEMDecryptorProviderBuilder().setProvider("BC");
        char[] charArray = info.password.toCharArray();
        PEMDecryptorProvider decProv = bcDecProvider.build(charArray);
        kp = converter.getKeyPair(((PEMEncryptedKeyPair)o).decryptKeyPair(decProv));
    }
    else {
        kp = converter.getKeyPair((PEMKeyPair)o);
    }

    PrivateKey privKey = kp.getPrivate();
    return privKey;
}
 
Example #24
Source File: CertificateSupplierModule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Provides
@PemFile
static ImmutableList<Object> providePemObjects(@Named("pemBytes") byte[] pemBytes) {
  PEMParser pemParser =
      new PEMParser(new InputStreamReader(new ByteArrayInputStream(pemBytes), UTF_8));
  ImmutableList.Builder<Object> listBuilder = new ImmutableList.Builder<>();
  Object obj;
  // PEMParser returns an object (private key, certificate, etc) each time readObject() is called,
  // until no more object is to be read from the file.
  while (true) {
    try {
      obj = pemParser.readObject();
      if (obj == null) {
        break;
      } else {
        listBuilder.add(obj);
      }
    } catch (IOException e) {
      throw new RuntimeException("Cannot parse PEM file correctly.", e);
    }
  }
  return listBuilder.build();
}
 
Example #25
Source File: PublicKeyReader.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Optional<PublicKey> publicKeyFrom(PEMParser reader) {
    try {
        Object readPEM = reader.readObject();
        if (readPEM instanceof SubjectPublicKeyInfo) {
            return Optional.of(new JcaPEMKeyConverter().getPublicKey((SubjectPublicKeyInfo) readPEM));
        }
        LOGGER.warn("Key is not an instance of SubjectPublicKeyInfo but of {}", readPEM);
        return Optional.empty();
    } catch (IOException e) {
        LOGGER.warn("Error when reading the PEM file", e);
        return Optional.empty();
    }
}
 
Example #26
Source File: EncryptionUtils.java    From snowflake-kafka-connector with Apache License 2.0 5 votes vote down vote up
public static PrivateKey parseEncryptedPrivateKey(String key, String passphrase)
{
  //remove header, footer, and line breaks
  key = key.replaceAll("-+[A-Za-z ]+-+", "");
  key = key.replaceAll("\\s", "");

  StringBuilder builder = new StringBuilder();
  builder.append("-----BEGIN ENCRYPTED PRIVATE KEY-----");
  for (int i = 0; i < key.length(); i++)
  {
    if (i % 64 == 0)
    {
      builder.append("\n");
    }
    builder.append(key.charAt(i));
  }
  builder.append("\n-----END ENCRYPTED PRIVATE KEY-----");
  key = builder.toString();
  Security.addProvider(new BouncyCastleFipsProvider());
  try
  {
    PEMParser pemParser = new PEMParser(new StringReader(key));
    PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo =
      (PKCS8EncryptedPrivateKeyInfo) pemParser.readObject();
    pemParser.close();
    InputDecryptorProvider pkcs8Prov =
      new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase.toCharArray());
    JcaPEMKeyConverter converter =
      new JcaPEMKeyConverter().setProvider(BouncyCastleFipsProvider.PROVIDER_NAME);
    PrivateKeyInfo decryptedPrivateKeyInfo =
      encryptedPrivateKeyInfo.decryptPrivateKeyInfo(pkcs8Prov);
    return converter.getPrivateKey(decryptedPrivateKeyInfo);
  } catch (Exception e)
  {
    throw SnowflakeErrors.ERROR_0018.getException(e);
  }
}
 
Example #27
Source File: PkiUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public static KeyPair fromPrivateKeyPem(String privateKeyContent) {
    BufferedReader br = new BufferedReader(new StringReader(privateKeyContent));
    Security.addProvider(new BouncyCastleProvider());
    try (PEMParser pp = new PEMParser(br)) {
        PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
        return new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
    } catch (IOException e) {
        LOGGER.info("Cannot parse KeyPair from private key pem content, skip it. {}", e.getMessage(), e);
    }
    return null;
}
 
Example #28
Source File: AzureKeyVaultClientAuthenticator.java    From ranger with Apache License 2.0 5 votes vote down vote up
private KeyCert readPem(String path, String password) throws IOException, CertificateException, OperatorCreationException, PKCSException {
	Security.addProvider(new BouncyCastleProvider());
	PEMParser pemParser = new PEMParser(new FileReader(new File(path)));
	PrivateKey privateKey = null;
	X509Certificate cert = null;
	Object object = pemParser.readObject();
	
	while (object != null) {
		JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
		if (object instanceof X509CertificateHolder) {
			cert = new JcaX509CertificateConverter().getCertificate((X509CertificateHolder) object);
		}
		if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
			PKCS8EncryptedPrivateKeyInfo pinfo = (PKCS8EncryptedPrivateKeyInfo) object;
			InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(password.toCharArray());
			PrivateKeyInfo info = pinfo.decryptPrivateKeyInfo(provider);
			privateKey = converter.getPrivateKey(info);
		} 
		if (object instanceof PrivateKeyInfo) {
			privateKey = converter.getPrivateKey((PrivateKeyInfo) object);
		}
		object = pemParser.readObject();
	}
	KeyCert keycert = new KeyCert();
	keycert.setCertificate(cert);
	keycert.setKey(privateKey);
	pemParser.close();
	return keycert;
}
 
Example #29
Source File: BouncyCastleSecurityProviderTool.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
@Override
public PrivateKey decodePemEncodedPrivateKey(Reader privateKeyReader, String password) {
    try (PEMParser pemParser = new PEMParser(privateKeyReader)) {
        Object keyPair = pemParser.readObject();

        // retrieve the PrivateKeyInfo from the returned keyPair object. if the key is encrypted, it needs to be
        // decrypted using the specified password first.
        PrivateKeyInfo keyInfo;
        if (keyPair instanceof PEMEncryptedKeyPair) {
            if (password == null) {
                throw new ImportException("Unable to import private key. Key is encrypted, but no password was provided.");
            }

            PEMDecryptorProvider decryptor = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());

            PEMKeyPair decryptedKeyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptor);

            keyInfo = decryptedKeyPair.getPrivateKeyInfo();
        } else {
            keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
        }

        return new JcaPEMKeyConverter().getPrivateKey(keyInfo);
    } catch (IOException e) {
        throw new ImportException("Unable to read PEM-encoded PrivateKey", e);
    }
}
 
Example #30
Source File: EbicsCertificateService.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
public X509Certificate convertToCertificate(String pemString)
    throws IOException, CertificateException {

  X509Certificate certificate;
  StringReader reader = new StringReader(pemString);
  try (final PEMParser pr = new PEMParser(reader)) {
    final X509CertificateHolder certificateHolder = (X509CertificateHolder) pr.readObject();
    certificate = new JcaX509CertificateConverter().getCertificate(certificateHolder);
  }

  return certificate;
}