Search in sources :

Example 1 with EncryptedPrivateKeyInfo

use of org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo in project robovm by robovm.

the class EncryptedPrivateKeyInfo method toASN1Primitive.

/**
     * Produce an object suitable for an ASN1OutputStream.
     * <pre>
     * EncryptedPrivateKeyInfo ::= SEQUENCE {
     *      encryptionAlgorithm AlgorithmIdentifier {{KeyEncryptionAlgorithms}},
     *      encryptedData EncryptedData
     * }
     *
     * EncryptedData ::= OCTET STRING
     *
     * KeyEncryptionAlgorithms ALGORITHM-IDENTIFIER ::= {
     *          ... -- For local profiles
     * }
     * </pre>
     */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(algId);
    v.add(data);
    return new DERSequence(v);
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector)

Example 2 with EncryptedPrivateKeyInfo

use of org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo 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 3 with EncryptedPrivateKeyInfo

use of org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo in project keystore-explorer by kaikramer.

the class Pkcs8Util method getEncryptionType.

/**
 * Detect if a PKCS #8 private key is encrypted or not.
 *
 * @param is
 *            Input stream containing PKCS #8 private key
 * @return Encryption type or null if not a valid PKCS #8 private key
 * @throws IOException
 *             If an I/O problem occurred
 */
public static EncryptionType getEncryptionType(InputStream is) throws IOException {
    byte[] pkcs8 = ReadUtil.readFully(is);
    PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(pkcs8));
    // PEM encoded?
    if (pemInfo != null) {
        String pemType = pemInfo.getType();
        // Encrypted in pem format?
        if (pemType.equals(Pkcs8Util.PKCS8_ENC_PVK_PEM_TYPE)) {
            return ENCRYPTED;
        } else // Unencrypted in pem format?
        if (pemType.equals(Pkcs8Util.PKCS8_UNENC_PVK_PEM_TYPE)) {
            return UNENCRYPTED;
        }
    }
    // In ASN.1 format?
    try {
        // Read in an ASN.1 and check structure against the following
        ASN1Primitive key = ASN1Primitive.fromByteArray(pkcs8);
        if (key instanceof ASN1Sequence) {
            ASN1Sequence sequence = (ASN1Sequence) key;
            // May be unencrypted
            if ((sequence.size() == 3) || (sequence.size() == 4)) {
                // @formatter:off
                /*
					 * Unencrypted PKCS #8 Private Key:
					 *
					 * PrivateKeyInfo ::= ASN1Sequence { version Version,
					 * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
					 * privateKey PrivateKey, attributes [0] IMPLICIT Attributes
					 * OPTIONAL }
					 *
					 * Version ::= ASN1Integer PrivateKeyAlgorithmIdentifier ::=
					 * AlgorithmIdentifier PrivateKey ::= OCTET STRING
					 * Attributes ::= SET OF Attribute
					 */
                // @formatter:on
                Object obj1 = sequence.getObjectAt(0);
                Object obj2 = sequence.getObjectAt(1);
                Object obj3 = sequence.getObjectAt(2);
                if (!(obj1 instanceof ASN1Integer)) {
                    return null;
                }
                ASN1Integer version = (ASN1Integer) obj1;
                if (!version.getValue().equals(BigInteger.ZERO)) {
                    return null;
                }
                if (!(obj2 instanceof ASN1Sequence)) {
                    return null;
                }
                if (!sequenceIsAlgorithmIdentifier((ASN1Sequence) obj2)) {
                    return null;
                }
                if (!(obj3 instanceof ASN1OctetString)) {
                    return null;
                }
                return UNENCRYPTED;
            } else // May be encrypted
            if (sequence.size() == 2) {
                // @formatter:off
                /*
					 * Encrypted PKCS #8 Private Key:
					 *
					 * EncryptedPrivateKeyInfo ::= ASN1Sequence {
					 * encryptionAlgorithm EncryptionAlgorithmIdentifier,
					 * encryptedData EncryptedData }
					 *
					 * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
					 * EncryptedData ::= OCTET STRING
					 */
                // @formatter:on
                Object obj1 = sequence.getObjectAt(0);
                Object obj2 = sequence.getObjectAt(1);
                if (!(obj1 instanceof ASN1Sequence)) {
                    return null;
                }
                if (!sequenceIsAlgorithmIdentifier((ASN1Sequence) obj1)) {
                    return null;
                }
                if (!(obj2 instanceof ASN1OctetString)) {
                    return null;
                }
                return ENCRYPTED;
            }
        }
    } catch (Exception ex) {
        // Structure not as expected for PKCS #8
        return null;
    }
    return null;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ByteArrayInputStream(java.io.ByteArrayInputStream) PemInfo(org.kse.utilities.pem.PemInfo) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CryptoException(org.kse.crypto.CryptoException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 4 with EncryptedPrivateKeyInfo

use of org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo in project certmgr by hdecarne.

the class DERCertReaderWriter method tryDecodeKey.

@Nullable
private static KeyPair tryDecodeKey(ASN1Primitive asn1Object, String resource, PasswordCallback password) throws IOException {
    PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = null;
    try {
        encryptedPrivateKeyInfo = new PKCS8EncryptedPrivateKeyInfo(EncryptedPrivateKeyInfo.getInstance(asn1Object));
    } catch (Exception e) {
        Exceptions.ignore(e);
    }
    PrivateKeyInfo privateKeyInfo = null;
    if (encryptedPrivateKeyInfo != null) {
        Throwable passwordException = null;
        while (privateKeyInfo == null) {
            char[] passwordChars = password.queryPassword(resource);
            if (passwordChars == null) {
                throw new PasswordRequiredException(resource, passwordException);
            }
            InputDecryptorProvider inputDecryptorProvider = INPUT_DECRYPTOR_BUILDER.build(passwordChars);
            try {
                privateKeyInfo = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(inputDecryptorProvider);
            } catch (PKCSException e) {
                passwordException = e;
            }
        }
    }
    try {
        privateKeyInfo = PrivateKeyInfo.getInstance(asn1Object);
    } catch (Exception e) {
        Exceptions.ignore(e);
    }
    KeyPair key = null;
    if (privateKeyInfo != null) {
        PrivateKey privateKey;
        try {
            String algorithmId = privateKeyInfo.getPrivateKeyAlgorithm().getAlgorithm().getId();
            KeyFactory keyFactory = JCA_JCE_HELPER.createKeyFactory(algorithmId);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded());
            privateKey = keyFactory.generatePrivate(keySpec);
        } catch (GeneralSecurityException e) {
            throw new CertProviderException(e);
        }
        key = KeyHelper.rebuildKeyPair(privateKey);
    }
    return key;
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) GeneralSecurityException(java.security.GeneralSecurityException) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) PasswordRequiredException(de.carne.certmgr.certs.PasswordRequiredException) PKCSException(org.bouncycastle.pkcs.PKCSException) CertProviderException(de.carne.certmgr.certs.CertProviderException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CertProviderException(de.carne.certmgr.certs.CertProviderException) GeneralSecurityException(java.security.GeneralSecurityException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) PasswordRequiredException(de.carne.certmgr.certs.PasswordRequiredException) InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) EncryptedPrivateKeyInfo(org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo) KeyFactory(java.security.KeyFactory) Nullable(de.carne.check.Nullable)

Example 5 with EncryptedPrivateKeyInfo

use of org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo in project xipki by xipki.

the class PrivateKeyCryptor method decrypt.

PrivateKey decrypt(PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo) throws P11TokenException {
    ParamUtil.requireNonNull("encryptedPrivateKeyInfo", encryptedPrivateKeyInfo);
    PrivateKeyInfo privateKeyInfo;
    synchronized (decryptorProvider) {
        try {
            privateKeyInfo = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(decryptorProvider);
        } catch (PKCSException ex) {
            throw new P11TokenException(ex.getMessage(), ex);
        }
    }
    AlgorithmIdentifier keyAlg = privateKeyInfo.getPrivateKeyAlgorithm();
    ASN1ObjectIdentifier keyAlgOid = keyAlg.getAlgorithm();
    String algoName;
    if (PKCSObjectIdentifiers.rsaEncryption.equals(keyAlgOid)) {
        algoName = "RSA";
    } else if (X9ObjectIdentifiers.id_dsa.equals(keyAlgOid)) {
        algoName = "DSA";
    } else if (X9ObjectIdentifiers.id_ecPublicKey.equals(keyAlgOid)) {
        algoName = "EC";
    } else {
        throw new P11TokenException("unknown private key algorithm " + keyAlgOid.getId());
    }
    try {
        KeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance(algoName, "BC");
        return keyFactory.generatePrivate(keySpec);
    } catch (IOException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException ex) {
        throw new P11TokenException(ex.getClass().getName() + ": " + ex.getMessage(), ex);
    }
}
Also used : P11TokenException(org.xipki.security.exception.P11TokenException) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) KeySpec(java.security.spec.KeySpec) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) PKCSException(org.bouncycastle.pkcs.PKCSException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) NoSuchProviderException(java.security.NoSuchProviderException) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) KeyFactory(java.security.KeyFactory)

Aggregations

IOException (java.io.IOException)5 PrivateKeyInfo (org.bouncycastle.asn1.pkcs.PrivateKeyInfo)5 GeneralSecurityException (java.security.GeneralSecurityException)4 KeyFactory (java.security.KeyFactory)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)4 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)4 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)3 EncryptedPrivateKeyInfo (org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo)3 PKCS8EncryptedPrivateKeyInfo (org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 KeyPair (java.security.KeyPair)2 PrivateKey (java.security.PrivateKey)2 SecretKeyFactory (javax.crypto.SecretKeyFactory)2 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)2 DEROctetString (org.bouncycastle.asn1.DEROctetString)2 DERSequence (org.bouncycastle.asn1.DERSequence)2 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)2 BufferedBlockCipher (org.bouncycastle.crypto.BufferedBlockCipher)2 CBCBlockCipher (org.bouncycastle.crypto.modes.CBCBlockCipher)2