Search in sources :

Example 26 with PEMKeyPair

use of org.bouncycastle.openssl.PEMKeyPair in project candlepin by candlepin.

the class PrivateKeyReaderTest method testReadEncryptedPKCS1.

@Test
public void testReadEncryptedPKCS1() throws Exception {
    String keyFile = "keys/pkcs1-aes256-encrypted.pem";
    try (InputStream keyStream = cl.getResourceAsStream(keyFile);
        Reader expectedReader = new InputStreamReader(cl.getResourceAsStream(keyFile))) {
        PrivateKey actualKey = new PrivateKeyReader().read(keyStream, "password");
        PEMEncryptedKeyPair expected = (PEMEncryptedKeyPair) new PEMParser(expectedReader).readObject();
        PEMDecryptorProvider provider = new JcePEMDecryptorProviderBuilder().setProvider(BC_PROVIDER).build(PASSWORD);
        PEMKeyPair decryptedInfo = expected.decryptKeyPair(provider);
        PrivateKey expectedKey = new JcaPEMKeyConverter().setProvider(BC_PROVIDER).getKeyPair(decryptedInfo).getPrivate();
        assertEquals(actualKey, expectedKey);
    }
}
Also used : PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PrivateKey(java.security.PrivateKey) InputStreamReader(java.io.InputStreamReader) PEMParser(org.bouncycastle.openssl.PEMParser) InputStream(java.io.InputStream) PEMDecryptorProvider(org.bouncycastle.openssl.PEMDecryptorProvider) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) Test(org.junit.Test)

Example 27 with PEMKeyPair

use of org.bouncycastle.openssl.PEMKeyPair in project box-java-sdk by box.

the class BoxDeveloperEditionAPIConnection method decryptPrivateKey.

private PrivateKey decryptPrivateKey() {
    PrivateKey decryptedPrivateKey;
    try {
        PEMParser keyReader = new PEMParser(new StringReader(this.privateKey));
        Object keyPair = keyReader.readObject();
        keyReader.close();
        if (keyPair instanceof PrivateKeyInfo) {
            PrivateKeyInfo keyInfo = (PrivateKeyInfo) keyPair;
            decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo);
        } else if (keyPair instanceof PEMEncryptedKeyPair) {
            JcePEMDecryptorProviderBuilder builder = new JcePEMDecryptorProviderBuilder();
            PEMDecryptorProvider decryptionProvider = builder.build(this.privateKeyPassword.toCharArray());
            keyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptionProvider);
            PrivateKeyInfo keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
            decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo);
        } else if (keyPair instanceof PKCS8EncryptedPrivateKeyInfo) {
            InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder().setProvider("BC").build(this.privateKeyPassword.toCharArray());
            PrivateKeyInfo keyInfo = ((PKCS8EncryptedPrivateKeyInfo) keyPair).decryptPrivateKeyInfo(pkcs8Prov);
            decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo);
        } else {
            PrivateKeyInfo keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
            decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo);
        }
    } catch (IOException e) {
        throw new BoxAPIException("Error parsing private key for Box Developer Edition.", e);
    } catch (OperatorCreationException e) {
        throw new BoxAPIException("Error parsing PKCS#8 private key for Box Developer Edition.", e);
    } catch (PKCSException e) {
        throw new BoxAPIException("Error parsing PKCS private key for Box Developer Edition.", e);
    }
    return decryptedPrivateKey;
}
Also used : PrivateKey(java.security.PrivateKey) PEMDecryptorProvider(org.bouncycastle.openssl.PEMDecryptorProvider) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) IOException(java.io.IOException) PKCSException(org.bouncycastle.pkcs.PKCSException) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMParser(org.bouncycastle.openssl.PEMParser) InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) StringReader(java.io.StringReader) JsonObject(com.eclipsesource.json.JsonObject) JceOpenSSLPKCS8DecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)

Example 28 with PEMKeyPair

use of org.bouncycastle.openssl.PEMKeyPair in project athenz by yahoo.

the class Utils method createKeyStore.

/**
 * Create a {@link KeyStore} from suppliers of {@link InputStream} for cert and key.
 *
 * @param athenzPublicCertInputStream      Supplier of the certificate input stream
 * @param athenzPublicCertLocationSupplier Supplier of the location of the certificate (for error logging)
 * @param athenzPrivateKeyInputStream      Supplier of the private key input stream
 * @param athenzPrivateKeyLocationSupplier Supplier of the location of the certificate (for error logging)
 * @return a KeyStore with loaded key and certificate
 * @throws KeyRefresherException in case of any key refresher errors processing the request
 * @throws IOException in case of any errors with reading files
 */
public static KeyStore createKeyStore(final Supplier<InputStream> athenzPublicCertInputStream, final Supplier<String> athenzPublicCertLocationSupplier, final Supplier<InputStream> athenzPrivateKeyInputStream, final Supplier<String> athenzPrivateKeyLocationSupplier) throws IOException, KeyRefresherException {
    List<? extends Certificate> certificates;
    PrivateKey privateKey;
    KeyStore keyStore = null;
    try (InputStream publicCertStream = athenzPublicCertInputStream.get();
        InputStream privateKeyStream = athenzPrivateKeyInputStream.get();
        PEMParser pemParser = new PEMParser(new InputStreamReader(privateKeyStream))) {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
        Object key = pemParser.readObject();
        if (key instanceof PEMKeyPair) {
            PrivateKeyInfo pKeyInfo = ((PEMKeyPair) key).getPrivateKeyInfo();
            privateKey = pemConverter.getPrivateKey(pKeyInfo);
        } else if (key instanceof PrivateKeyInfo) {
            privateKey = pemConverter.getPrivateKey((PrivateKeyInfo) key);
        } else {
            throw new KeyRefresherException("Unknown object type: " + (key == null ? "null" : key.getClass().getName()));
        }
        // noinspection unchecked
        certificates = (List<? extends Certificate>) cf.generateCertificates(publicCertStream);
        if (certificates.isEmpty()) {
            throw new KeyRefresherException("Certificate file contains empty certificate or an invalid certificate.");
        }
        // We are going to assume that the first one is the main certificate which will be used for the alias
        String alias = ((X509Certificate) certificates.get(0)).getSubjectX500Principal().getName();
        if (LOG.isDebugEnabled()) {
            LOG.debug("{} number of certificates found. Using {} alias to create the keystore", certificates.size(), alias);
        }
        keyStore = KeyStore.getInstance(DEFAULT_KEYSTORE_TYPE);
        keyStore.load(null);
        keyStore.setKeyEntry(alias, privateKey, KEYSTORE_PASSWORD, certificates.toArray((Certificate[]) new X509Certificate[certificates.size()]));
    } catch (CertificateException | NoSuchAlgorithmException ex) {
        String keyStoreFailMsg = "Unable to load " + athenzPublicCertLocationSupplier.get() + " as a KeyStore. Please check the validity of the file.";
        throw new KeyRefresherException(keyStoreFailMsg, ex);
    } catch (KeyStoreException ex) {
        LOG.error("No Provider supports a KeyStoreSpi implementation for the specified type.", ex);
    }
    return keyStore;
}
Also used : JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) CertificateException(java.security.cert.CertificateException) CertificateFactory(java.security.cert.CertificateFactory) PEMParser(org.bouncycastle.openssl.PEMParser) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 29 with PEMKeyPair

use of org.bouncycastle.openssl.PEMKeyPair in project fabric-sdk-java by hyperledger.

the class CryptoPrimitivesTest method setUp.

@Before
public void setUp() throws Exception {
    // TODO should do this in @BeforeClass. Need to find out how to get to
    // files from static junit method
    BufferedInputStream bis = new BufferedInputStream(this.getClass().getResourceAsStream("/ca.crt"));
    testCACert = cf.generateCertificate(bis);
    bis.close();
    crypto.addCACertificateToTrustStore(testCACert, "ca");
    bis = new BufferedInputStream(this.getClass().getResourceAsStream("/keypair-signed.crt"));
    Certificate cert = cf.generateCertificate(bis);
    bis.close();
    // TODO: get PEM file without dropping down to BouncyCastle ?
    PEMParser pem = new PEMParser(new FileReader(this.getClass().getResource("/keypair-signed.key").getFile()));
    PEMKeyPair bcKeyPair = (PEMKeyPair) pem.readObject();
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bcKeyPair.getPrivateKeyInfo().getEncoded());
    PrivateKey key = kf.generatePrivate(keySpec);
    Certificate[] certificates = new Certificate[] { cert, testCACert };
    crypto.getTrustStore().setKeyEntry("key", key, "123456".toCharArray(), certificates);
    pem.close();
}
Also used : PrivateKey(java.security.PrivateKey) PEMParser(org.bouncycastle.openssl.PEMParser) BufferedInputStream(java.io.BufferedInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) FileReader(java.io.FileReader) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) Before(org.junit.Before)

Example 30 with PEMKeyPair

use of org.bouncycastle.openssl.PEMKeyPair in project fabric-sdk-java by hyperledger.

the class CryptoPrimitives method bytesToPrivateKey.

/**
 * 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)));
        logger.debug("found private key with type " + po.getType());
        if (po.getType().equals("PRIVATE KEY")) {
            pk = new JcaPEMKeyConverter().getPrivateKey((PrivateKeyInfo) pem.readObject());
        } else {
            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;
}
Also used : PemReader(org.bouncycastle.util.io.pem.PemReader) PemObject(org.bouncycastle.util.io.pem.PemObject) PrivateKey(java.security.PrivateKey) ECPrivateKey(java.security.interfaces.ECPrivateKey) PEMParser(org.bouncycastle.openssl.PEMParser) StringReader(java.io.StringReader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) KeyStoreException(java.security.KeyStoreException) CertPathValidatorException(java.security.cert.CertPathValidatorException) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException)

Aggregations

PEMKeyPair (org.bouncycastle.openssl.PEMKeyPair)37 PEMParser (org.bouncycastle.openssl.PEMParser)35 JcaPEMKeyConverter (org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter)28 PrivateKeyInfo (org.bouncycastle.asn1.pkcs.PrivateKeyInfo)17 IOException (java.io.IOException)13 InputStreamReader (java.io.InputStreamReader)13 PrivateKey (java.security.PrivateKey)12 PEMEncryptedKeyPair (org.bouncycastle.openssl.PEMEncryptedKeyPair)12 StringReader (java.io.StringReader)11 PEMDecryptorProvider (org.bouncycastle.openssl.PEMDecryptorProvider)11 JcePEMDecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder)11 InputStream (java.io.InputStream)10 KeyPair (java.security.KeyPair)8 Reader (java.io.Reader)7 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)7 PKCS8EncryptedPrivateKeyInfo (org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)7 JceOpenSSLPKCS8DecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder)6 InputDecryptorProvider (org.bouncycastle.operator.InputDecryptorProvider)6 PemObject (org.bouncycastle.util.io.pem.PemObject)6 KeyFactory (java.security.KeyFactory)5