Search in sources :

Example 6 with PrivateKeyInfo

use of org.gudy.bouncycastle.asn1.pkcs.PrivateKeyInfo in project android_packages_apps_Settings by LineageOS.

the class CredentialStorage method isHardwareBackedKey.

private boolean isHardwareBackedKey(byte[] keyData) {
    try {
        ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(keyData));
        PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
        String algOid = pki.getAlgorithmId().getAlgorithm().getId();
        String algName = new AlgorithmId(new ObjectIdentifier(algOid)).getName();
        return KeyChain.isBoundKeyAlgorithm(algName);
    } catch (IOException e) {
        Log.e(TAG, "Failed to parse key data");
        return false;
    }
}
Also used : ASN1InputStream(com.android.org.bouncycastle.asn1.ASN1InputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) AlgorithmId(sun.security.x509.AlgorithmId) IOException(java.io.IOException) PrivateKeyInfo(com.android.org.bouncycastle.asn1.pkcs.PrivateKeyInfo) ObjectIdentifier(sun.security.util.ObjectIdentifier)

Example 7 with PrivateKeyInfo

use of org.gudy.bouncycastle.asn1.pkcs.PrivateKeyInfo in project athenz by yahoo.

the class Utils method createKeyStore.

/**
 * @param athensPublicKey the location on the public key file
 * @param athensPrivateKey the location of the private key file
 * @return a KeyStore with loaded key and certificate
 * @throws Exception KeyStore generation can throw Exception for many reasons
 */
public static KeyStore createKeyStore(final String athensPublicKey, final String athensPrivateKey) throws Exception {
    final CertificateFactory cf = CertificateFactory.getInstance("X.509");
    final JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
    X509Certificate certificate;
    PrivateKey privateKey = null;
    final InputStream publicCertStream;
    final InputStream privateKeyStream;
    try {
        if (Paths.get(athensPublicKey).isAbsolute() && Paths.get(athensPrivateKey).isAbsolute()) {
            // Can not cover this branch in unit test. Can not refer any files by absolute paths
            File certFile = new File(athensPublicKey);
            File keyFile = new File(athensPrivateKey);
            while (!certFile.exists() || !keyFile.exists()) {
                LOG.error("Missing Athenz public or private key files");
                Thread.sleep(1000);
            }
            publicCertStream = new FileInputStream(athensPublicKey);
            privateKeyStream = new FileInputStream(athensPrivateKey);
        } else {
            publicCertStream = Resources.getResource(athensPublicKey).openStream();
            privateKeyStream = Resources.getResource(athensPrivateKey).openStream();
        }
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
    try (PEMParser pemParser = new PEMParser(new InputStreamReader(privateKeyStream))) {
        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 IllegalStateException("Unknown object type: " + key.getClass().getName());
        }
    } catch (IOException e) {
        throw new IllegalStateException("Unable to parse private key", e);
    }
    certificate = (X509Certificate) cf.generateCertificate(publicCertStream);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    String alias = certificate.getSubjectX500Principal().getName();
    keyStore.load(null);
    keyStore.setKeyEntry(alias, privateKey, KEYSTORE_PASSWORD.toCharArray(), new X509Certificate[] { certificate });
    return keyStore;
}
Also used : PrivateKey(java.security.PrivateKey) InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) FileInputStream(java.io.FileInputStream) PEMParser(org.bouncycastle.openssl.PEMParser) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) File(java.io.File) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 8 with PrivateKeyInfo

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

the class OpenSslPvkUtil method load.

/**
 * Load an unencrypted OpenSSL private key from the stream. The encoding of
 * the private key may be PEM or DER.
 *
 * @param is
 *            Stream to load the unencrypted private key from
 * @return The private key
 * @throws PrivateKeyEncryptedException
 *             If private key is encrypted
 * @throws CryptoException
 *             Problem encountered while loading the private key
 * @throws IOException
 *             An I/O error occurred
 */
public static PrivateKey load(InputStream is) throws CryptoException, IOException {
    byte[] streamContents = ReadUtil.readFully(is);
    EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));
    if (encType == null) {
        throw new CryptoException(res.getString("NotValidOpenSsl.exception.message"));
    }
    if (encType == ENCRYPTED) {
        throw new PrivateKeyEncryptedException(res.getString("OpenSslIsEncrypted.exception.message"));
    }
    // Check if stream is PEM encoded
    PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents));
    if (pemInfo != null) {
        // It is - get DER from PEM
        streamContents = pemInfo.getContent();
    }
    try {
        // Read OpenSSL DER structure
        ASN1InputStream asn1InputStream = new ASN1InputStream(streamContents);
        ASN1Primitive openSsl = asn1InputStream.readObject();
        asn1InputStream.close();
        if (openSsl instanceof ASN1Sequence) {
            ASN1Sequence seq = (ASN1Sequence) openSsl;
            if (seq.size() == 9) {
                // RSA private key
                BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
                BigInteger modulus = ((ASN1Integer) seq.getObjectAt(1)).getValue();
                BigInteger publicExponent = ((ASN1Integer) seq.getObjectAt(2)).getValue();
                BigInteger privateExponent = ((ASN1Integer) seq.getObjectAt(3)).getValue();
                BigInteger primeP = ((ASN1Integer) seq.getObjectAt(4)).getValue();
                BigInteger primeQ = ((ASN1Integer) seq.getObjectAt(5)).getValue();
                BigInteger primeExponentP = ((ASN1Integer) seq.getObjectAt(6)).getValue();
                BigInteger primeExponenetQ = ((ASN1Integer) seq.getObjectAt(7)).getValue();
                BigInteger crtCoefficient = ((ASN1Integer) seq.getObjectAt(8)).getValue();
                if (!version.equals(VERSION)) {
                    throw new CryptoException(MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue()));
                }
                RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponenetQ, crtCoefficient);
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                return keyFactory.generatePrivate(rsaPrivateCrtKeySpec);
            } else if (seq.size() == 6) {
                // DSA private key
                BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
                BigInteger primeModulusP = ((ASN1Integer) seq.getObjectAt(1)).getValue();
                BigInteger primeQ = ((ASN1Integer) seq.getObjectAt(2)).getValue();
                BigInteger generatorG = ((ASN1Integer) seq.getObjectAt(3)).getValue();
                // publicExponentY not req for pvk: sequence.getObjectAt(4);
                BigInteger secretExponentX = ((ASN1Integer) seq.getObjectAt(5)).getValue();
                if (!version.equals(VERSION)) {
                    throw new CryptoException(MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue()));
                }
                DSAPrivateKeySpec dsaPrivateKeySpec = new DSAPrivateKeySpec(secretExponentX, primeModulusP, primeQ, generatorG);
                KeyFactory keyFactory = KeyFactory.getInstance("DSA");
                return keyFactory.generatePrivate(dsaPrivateKeySpec);
            } else if (seq.size() >= 2) {
                // EC private key (RFC 5915)
                org.bouncycastle.asn1.sec.ECPrivateKey pKey = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(seq);
                AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, pKey.getParameters());
                PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey);
                return new JcaPEMKeyConverter().getPrivateKey(privInfo);
            } else {
                throw new CryptoException(MessageFormat.format(res.getString("OpenSslSequenceIncorrectSize.exception.message"), "" + seq.size()));
            }
        } else {
            throw new CryptoException(res.getString("OpenSslSequenceNotFound.exception.message"));
        }
    } catch (Exception ex) {
        throw new CryptoException(res.getString("NoLoadOpenSslPrivateKey.exception.message"), ex);
    }
}
Also used : RSAPrivateCrtKeySpec(java.security.spec.RSAPrivateCrtKeySpec) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) PemInfo(org.kse.utilities.pem.PemInfo) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) CryptoException(org.kse.crypto.CryptoException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DSAPrivateKeySpec(java.security.spec.DSAPrivateKeySpec) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ByteArrayInputStream(java.io.ByteArrayInputStream) BigInteger(java.math.BigInteger) CryptoException(org.kse.crypto.CryptoException) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) KeyFactory(java.security.KeyFactory) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 9 with PrivateKeyInfo

use of org.gudy.bouncycastle.asn1.pkcs.PrivateKeyInfo 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 10 with PrivateKeyInfo

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

the class EccUtil method convertToECPrivateKeyStructure.

/**
 * Converts PKCS#8 EC private key (RFC 5208 ASN.1 PrivateKeyInfo structure) to "traditional" OpenSSL
 * ASN.1 structure ECPrivateKey from RFC 5915. As ECPrivateKey is already in the PrivateKey field of PrivateKeyInfo,
 * this must only be extracted:
 *
 * SEQUENCE {
 *	  INTEGER 0
 *	  SEQUENCE {
 *	    OBJECT IDENTIFIER ecPublicKey (1 2 840 10045 2 1)
 *	    OBJECT IDENTIFIER prime256v1 (1 2 840 10045 3 1 7)
 *	    }
 *	  OCTET STRING, encapsulates {
 *	    SEQUENCE {
 *	      INTEGER 1
 *	      OCTET STRING
 *	        17 12 CA 42 16 79 1B 45    ...B.y.E
 *	        ...
 *	        C8 B2 66 0A E5 60 50 0B
 *	      [0] {
 *	        OBJECT IDENTIFIER prime256v1 (1 2 840 10045 3 1 7)
 *	        }
 *	      [1] {
 *	        BIT STRING
 *	          04 61 C0 08 B4 89 A0 50    .a.....P
 *            ...
 *	          AE D5 ED C3 4D 0E 47 91    ....M.G.
 *	          89                         .
 *	        }
 *	      }
 *	    }
 *	  }
 *
 * @param ecPrivateKey An EC key
 * @return Object holding ASN1 ECPrivateKey structure
 * @throws IOException When ECPrivateKey structure in PrivateKeyInfo's PrivateKey field cannot be parsed
 */
public static org.bouncycastle.asn1.sec.ECPrivateKey convertToECPrivateKeyStructure(ECPrivateKey ecPrivateKey) throws IOException {
    byte[] encoded = ecPrivateKey.getEncoded();
    PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(encoded);
    ASN1Encodable privateKey = privateKeyInfo.parsePrivateKey();
    return org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(privateKey);
}
Also used : ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Aggregations

PrivateKeyInfo (org.bouncycastle.asn1.pkcs.PrivateKeyInfo)46 IOException (java.io.IOException)30 JcaPEMKeyConverter (org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter)26 PEMParser (org.bouncycastle.openssl.PEMParser)23 PrivateKey (java.security.PrivateKey)21 PEMKeyPair (org.bouncycastle.openssl.PEMKeyPair)18 PKCS8EncryptedPrivateKeyInfo (org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)18 ByteArrayInputStream (java.io.ByteArrayInputStream)13 InputDecryptorProvider (org.bouncycastle.operator.InputDecryptorProvider)13 JceOpenSSLPKCS8DecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder)11 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)9 PemObject (org.bouncycastle.util.io.pem.PemObject)9 ASN1InputStream (com.android.org.bouncycastle.asn1.ASN1InputStream)8 PrivateKeyInfo (com.android.org.bouncycastle.asn1.pkcs.PrivateKeyInfo)8 StringReader (java.io.StringReader)8 JcePEMDecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder)8 ObjectIdentifier (sun.security.util.ObjectIdentifier)8 AlgorithmId (sun.security.x509.AlgorithmId)8 GeneralSecurityException (java.security.GeneralSecurityException)7 KeyPair (java.security.KeyPair)7