Search in sources :

Example 1 with JceOpenSSLPKCS8DecryptorProviderBuilder

use of org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder in project keystore-explorer by kaikramer.

the class Pkcs8Util method loadEncrypted.

/**
 * Load an encrypted PKCS #8 private key from the specified stream. The
 * encoding of the private key may be PEM or DER.
 *
 * @param is
 *            Stream load the encrypted private key from
 * @param password
 *            Password to decrypt
 * @return The private key
 * @throws PrivateKeyUnencryptedException
 *             If private key is unencrypted
 * @throws PrivateKeyPbeNotSupportedException
 *             If private key PBE algorithm is not supported
 * @throws CryptoException
 *             Problem encountered while loading the private key
 * @throws IOException
 *             If an I/O error occurred
 */
public static PrivateKey loadEncrypted(InputStream is, Password password) throws CryptoException, IOException {
    byte[] streamContents = ReadUtil.readFully(is);
    // Check PKCS#8 is encrypted
    EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));
    if (encType == null) {
        // Not a valid PKCS #8 private key
        throw new CryptoException(res.getString("NotValidPkcs8.exception.message"));
    }
    if (encType == UNENCRYPTED) {
        throw new PrivateKeyUnencryptedException(res.getString("Pkcs8IsEncrypted.exception.message"));
    }
    // Check if stream is PEM encoded
    PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents));
    byte[] encPvk = null;
    if (pemInfo != null) {
        // It is - get DER from PEM
        encPvk = pemInfo.getContent();
    }
    // If we haven't got the encrypted bytes via PEM then assume it is DER encoded
    if (encPvk == null) {
        encPvk = streamContents;
    }
    // try to read PKCS#8 info
    PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = null;
    try {
        encryptedPrivateKeyInfo = new PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(encPvk));
    } catch (Exception e) {
        // Not a valid PKCS #8 private key
        throw new CryptoException(res.getString("NotValidPkcs8.exception.message"));
    }
    // decrypt and create PrivateKey object from ASN.1 structure
    try {
        InputDecryptorProvider decProv = new JceOpenSSLPKCS8DecryptorProviderBuilder().setProvider("BC").build(password.toCharArray());
        PrivateKeyInfo privateKeyInfo = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(decProv);
        return new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
    } catch (Exception ex) {
        throw new CryptoException(res.getString("NoLoadPkcs8PrivateKey.exception.message"), ex);
    }
}
Also used : InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) ByteArrayInputStream(java.io.ByteArrayInputStream) PemInfo(org.kse.utilities.pem.PemInfo) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) JceOpenSSLPKCS8DecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) CryptoException(org.kse.crypto.CryptoException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CryptoException(org.kse.crypto.CryptoException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) EncryptedPrivateKeyInfo(javax.crypto.EncryptedPrivateKeyInfo) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)

Example 2 with JceOpenSSLPKCS8DecryptorProviderBuilder

use of org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder in project neo4j by neo4j.

the class PkiUtils method loadPrivateKey.

public static PrivateKey loadPrivateKey(Path privateKeyFile, String passPhrase) throws IOException {
    if (passPhrase == null) {
        passPhrase = "";
    }
    try (PEMParser r = new PEMParser(Files.newBufferedReader(privateKeyFile))) {
        Object pemObject = r.readObject();
        final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(PROVIDER);
        if (// -----BEGIN RSA/DSA/EC PRIVATE KEY----- Proc-Type: 4,ENCRYPTED
        pemObject instanceof PEMEncryptedKeyPair) {
            final PEMEncryptedKeyPair ckp = (PEMEncryptedKeyPair) pemObject;
            final PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passPhrase.toCharArray());
            return converter.getKeyPair(ckp.decryptKeyPair(decProv)).getPrivate();
        } else if (// -----BEGIN ENCRYPTED PRIVATE KEY-----
        pemObject instanceof PKCS8EncryptedPrivateKeyInfo) {
            try {
                final PKCS8EncryptedPrivateKeyInfo encryptedInfo = (PKCS8EncryptedPrivateKeyInfo) pemObject;
                final InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passPhrase.toCharArray());
                final PrivateKeyInfo privateKeyInfo = encryptedInfo.decryptPrivateKeyInfo(provider);
                return converter.getPrivateKey(privateKeyInfo);
            } catch (PKCSException | OperatorCreationException e) {
                throw new IOException("Unable to decrypt private key.", e);
            }
        } else if (// -----BEGIN PRIVATE KEY-----
        pemObject instanceof PrivateKeyInfo) {
            return converter.getPrivateKey((PrivateKeyInfo) pemObject);
        } else if (// -----BEGIN RSA/DSA/EC PRIVATE KEY-----
        pemObject instanceof PEMKeyPair) {
            return converter.getKeyPair((PEMKeyPair) pemObject).getPrivate();
        } else {
            throw new IOException("Unrecognized private key format.");
        }
    }
}
Also used : PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMParser(org.bouncycastle.openssl.PEMParser) InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) PEMDecryptorProvider(org.bouncycastle.openssl.PEMDecryptorProvider) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) PemObject(org.bouncycastle.util.io.pem.PemObject) JceOpenSSLPKCS8DecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) IOException(java.io.IOException) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)

Example 3 with JceOpenSSLPKCS8DecryptorProviderBuilder

use of org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder in project athenz by yahoo.

the class Crypto method loadPrivateKey.

public static PrivateKey loadPrivateKey(Reader reader, String pwd) throws CryptoException {
    try (PEMParser pemReader = new PEMParser(reader)) {
        PrivateKey privKey = null;
        X9ECParameters ecParam = null;
        Object pemObj = pemReader.readObject();
        if (pemObj instanceof ASN1ObjectIdentifier) {
            // make sure this is EC Parameter we're handling. In which case
            // we'll store it and read the next object which should be our
            // EC Private Key
            ASN1ObjectIdentifier ecOID = (ASN1ObjectIdentifier) pemObj;
            ecParam = ECNamedCurveTable.getByOID(ecOID);
            // /CLOVER:OFF
            if (ecParam == null) {
                throw new PEMException("Unable to find EC Parameter for the given curve oid: " + ((ASN1ObjectIdentifier) pemObj).getId());
            }
            // /CLOVER:ON
            pemObj = pemReader.readObject();
        } else if (pemObj instanceof X9ECParameters) {
            ecParam = (X9ECParameters) pemObj;
            pemObj = pemReader.readObject();
        }
        if (pemObj instanceof PEMKeyPair) {
            PrivateKeyInfo pKeyInfo = ((PEMKeyPair) pemObj).getPrivateKeyInfo();
            JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
            privKey = pemConverter.getPrivateKey(pKeyInfo);
        // /CLOVER:OFF
        } else if (pemObj instanceof PKCS8EncryptedPrivateKeyInfo) {
            // /CLOVER:ON
            PKCS8EncryptedPrivateKeyInfo pKeyInfo = (PKCS8EncryptedPrivateKeyInfo) pemObj;
            if (pwd == null) {
                throw new CryptoException("No password specified to decrypt encrypted private key");
            }
            // Decrypt the private key with the specified password
            InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder().setProvider(BC_PROVIDER).build(pwd.toCharArray());
            PrivateKeyInfo privateKeyInfo = pKeyInfo.decryptPrivateKeyInfo(pkcs8Prov);
            JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
            privKey = pemConverter.getPrivateKey(privateKeyInfo);
        }
        if (ecParam != null && privKey != null && ECDSA.equals(privKey.getAlgorithm())) {
            ECParameterSpec ecSpec = new ECParameterSpec(ecParam.getCurve(), ecParam.getG(), ecParam.getN(), ecParam.getH(), ecParam.getSeed());
            KeyFactory keyFactory = KeyFactory.getInstance(getECDSAAlgo(), getKeyFactoryProvider());
            ECPrivateKeySpec keySpec = new ECPrivateKeySpec(((BCECPrivateKey) privKey).getS(), ecSpec);
            privKey = keyFactory.generatePrivate(keySpec);
        }
        return privKey;
    // /CLOVER:OFF
    } catch (PEMException e) {
        LOG.error("loadPrivateKey: Caught PEMException, problem with format of key detected.");
        throw new CryptoException(e);
    } catch (NoSuchProviderException e) {
        LOG.error("loadPrivateKey: Caught NoSuchProviderException, check to make sure the provider is loaded correctly.");
        throw new CryptoException(e);
    } catch (NoSuchAlgorithmException e) {
        LOG.error("loadPrivateKey: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider.");
        throw new CryptoException(e);
    } catch (InvalidKeySpecException e) {
        LOG.error("loadPrivateKey: Caught InvalidKeySpecException, invalid key spec is being used.");
        throw new CryptoException(e);
    } catch (OperatorCreationException e) {
        LOG.error("loadPrivateKey: Caught OperatorCreationException when creating JceOpenSSLPKCS8DecryptorProviderBuilder.");
        throw new CryptoException(e);
    } catch (PKCSException e) {
        LOG.error("loadPrivateKey: Caught PKCSException when decrypting private key.");
        throw new CryptoException(e);
    } catch (IOException e) {
        LOG.error("loadPrivateKey: Caught IOException, while trying to read key.");
        throw new CryptoException(e);
    }
// /CLOVER:ON
}
Also used : BCECPrivateKey(org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey) ECPrivateKeySpec(org.bouncycastle.jce.spec.ECPrivateKeySpec) X9ECParameters(org.bouncycastle.asn1.x9.X9ECParameters) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) PKCSException(org.bouncycastle.pkcs.PKCSException) PEMParser(org.bouncycastle.openssl.PEMParser) InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) ECParameterSpec(org.bouncycastle.jce.spec.ECParameterSpec) PEMException(org.bouncycastle.openssl.PEMException) PemObject(org.bouncycastle.util.io.pem.PemObject) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) JceOpenSSLPKCS8DecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)

Example 4 with JceOpenSSLPKCS8DecryptorProviderBuilder

use of org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder 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 5 with JceOpenSSLPKCS8DecryptorProviderBuilder

use of org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder in project midpoint by Evolveum.

the class RemoteModuleWebSecurityConfiguration method getPrivateKey.

protected static PrivateKey getPrivateKey(AbstractSimpleKeyType key, Protector protector) throws EncryptionException, IOException, PKCSException, OperatorCreationException {
    if (key == null) {
        return null;
    }
    PrivateKey pkey = null;
    String stringPrivateKey = protector.decryptString(key.getPrivateKey());
    String stringPassphrase = protector.decryptString(key.getPassphrase());
    if (hasText(stringPrivateKey)) {
        Object obj;
        PEMParser parser = new PEMParser(new CharArrayReader(stringPrivateKey.toCharArray()));
        obj = parser.readObject();
        parser.close();
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        if (obj == null) {
            throw new EncryptionException("Unable to decode PEM key:" + key.getPrivateKey());
        } else if (obj instanceof PEMEncryptedKeyPair) {
            // Encrypted key - we will use provided password
            PEMEncryptedKeyPair ckp = (PEMEncryptedKeyPair) obj;
            char[] passarray = (ofNullable(stringPassphrase).orElse("")).toCharArray();
            PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passarray);
            KeyPair kp = converter.getKeyPair(ckp.decryptKeyPair(decProv));
            pkey = kp.getPrivate();
        } else if (obj instanceof PEMKeyPair) {
            // Unencrypted key - no password needed
            PEMKeyPair ukp = (PEMKeyPair) obj;
            KeyPair kp = converter.getKeyPair(ukp);
            pkey = kp.getPrivate();
        } else if (obj instanceof PrivateKeyInfo) {
            // Encrypted key - we will use provided password
            PrivateKeyInfo pk = (PrivateKeyInfo) obj;
            pkey = converter.getPrivateKey(pk);
        } else if (obj instanceof PKCS8EncryptedPrivateKeyInfo) {
            // Encrypted key - we will use provided password
            PKCS8EncryptedPrivateKeyInfo cpk = (PKCS8EncryptedPrivateKeyInfo) obj;
            char[] passarray = (ofNullable(stringPassphrase).orElse("")).toCharArray();
            final InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passarray);
            pkey = converter.getPrivateKey(cpk.decryptPrivateKeyInfo(provider));
        } else {
            throw new EncryptionException("Unable get private key from " + obj);
        }
    }
    return pkey;
}
Also used : PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) PEMDecryptorProvider(org.bouncycastle.openssl.PEMDecryptorProvider) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMParser(org.bouncycastle.openssl.PEMParser) InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) JceOpenSSLPKCS8DecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)

Aggregations

PrivateKeyInfo (org.bouncycastle.asn1.pkcs.PrivateKeyInfo)10 JcaPEMKeyConverter (org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter)10 JceOpenSSLPKCS8DecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder)10 InputDecryptorProvider (org.bouncycastle.operator.InputDecryptorProvider)10 PKCS8EncryptedPrivateKeyInfo (org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)10 PEMParser (org.bouncycastle.openssl.PEMParser)7 PEMKeyPair (org.bouncycastle.openssl.PEMKeyPair)6 JcePEMDecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder)5 PrivateKey (java.security.PrivateKey)4 PEMDecryptorProvider (org.bouncycastle.openssl.PEMDecryptorProvider)4 PEMEncryptedKeyPair (org.bouncycastle.openssl.PEMEncryptedKeyPair)4 PemObject (org.bouncycastle.util.io.pem.PemObject)4 IOException (java.io.IOException)3 PKCSException (org.bouncycastle.pkcs.PKCSException)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 GeneralSecurityException (java.security.GeneralSecurityException)2 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)2 EncryptedPrivateKeyInfo (javax.crypto.EncryptedPrivateKeyInfo)2 BouncyCastleProvider (org.bouncycastle.jce.provider.BouncyCastleProvider)2 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)2