Search in sources :

Example 11 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project Resurrection_packages_apps_Settings by ResurrectionRemix.

the class CredentialStorage method isHardwareBackedKey.

private boolean isHardwareBackedKey(byte[] keyData) {
    try {
        final ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(keyData));
        final PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
        final String algOid = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();
        final 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 12 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project vespa by vespa-engine.

the class PemKeyStore method loadPrivateKey.

private void loadPrivateKey(PEMParser parser) {
    try {
        Object object = parser.readObject();
        PrivateKeyInfo privateKeyInfo;
        if (object instanceof PEMKeyPair) {
            // Legacy PKCS1
            privateKeyInfo = ((PEMKeyPair) object).getPrivateKeyInfo();
        } else if (object instanceof PrivateKeyInfo) {
            // PKCS8
            privateKeyInfo = (PrivateKeyInfo) object;
        } else {
            throw new UnsupportedOperationException("Expected " + PrivateKeyInfo.class + " or " + PEMKeyPair.class + ", got " + object.getClass());
        }
        Object nextObject = parser.readObject();
        if (nextObject != null) {
            throw new UnsupportedOperationException("Expected a single private key, but found a second element " + nextObject.getClass());
        }
        setPrivateKey(privateKeyInfo);
    } catch (Exception e) {
        throw throwUnchecked(e);
    }
}
Also used : PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) PEMException(org.bouncycastle.openssl.PEMException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UncheckedIOException(java.io.UncheckedIOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 13 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo 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 14 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project karaf by apache.

the class KeyPairLoader method getKeyPair.

public static KeyPair getKeyPair(InputStream is, String password) throws GeneralSecurityException, IOException {
    try (PEMParser parser = new PEMParser(new InputStreamReader(is))) {
        Object o = parser.readObject();
        JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
        if (o instanceof PEMEncryptedKeyPair) {
            if (password == null) {
                throw new GeneralSecurityException("A password must be supplied to read an encrypted key pair");
            }
            JcePEMDecryptorProviderBuilder decryptorBuilder = new JcePEMDecryptorProviderBuilder();
            PEMDecryptorProvider pemDecryptor = decryptorBuilder.build(password.toCharArray());
            o = pemConverter.getKeyPair(((PEMEncryptedKeyPair) o).decryptKeyPair(pemDecryptor));
        } else if (o instanceof PKCS8EncryptedPrivateKeyInfo) {
            if (password == null) {
                throw new GeneralSecurityException("A password must be supplied to read an encrypted key pair");
            }
            JceOpenSSLPKCS8DecryptorProviderBuilder jce = new JceOpenSSLPKCS8DecryptorProviderBuilder();
            try {
                InputDecryptorProvider decProv = jce.build(password.toCharArray());
                o = ((PKCS8EncryptedPrivateKeyInfo) o).decryptPrivateKeyInfo(decProv);
            } catch (OperatorCreationException | PKCSException ex) {
                LOGGER.debug("Error decrypting key pair", ex);
                throw new GeneralSecurityException("Error decrypting key pair", ex);
            }
        }
        if (o instanceof PEMKeyPair) {
            return pemConverter.getKeyPair((PEMKeyPair) o);
        } else if (o instanceof KeyPair) {
            return (KeyPair) o;
        } else if (o instanceof PrivateKeyInfo) {
            PrivateKey privateKey = pemConverter.getPrivateKey((PrivateKeyInfo) o);
            PublicKey publicKey = convertPrivateToPublicKey(privateKey);
            if (publicKey != null) {
                return new KeyPair(publicKey, privateKey);
            }
        }
    }
    throw new GeneralSecurityException("Failed to parse input stream");
}
Also used : KeyPair(java.security.KeyPair) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) ECPrivateKey(java.security.interfaces.ECPrivateKey) PrivateKey(java.security.PrivateKey) InputStreamReader(java.io.InputStreamReader) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) 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) JceOpenSSLPKCS8DecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)

Example 15 with PrivateKeyInfo

use of com.github.zhenwei.core.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)

Aggregations

PrivateKeyInfo (org.bouncycastle.asn1.pkcs.PrivateKeyInfo)100 IOException (java.io.IOException)69 JcaPEMKeyConverter (org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter)53 PEMParser (org.bouncycastle.openssl.PEMParser)49 PrivateKey (java.security.PrivateKey)37 PEMKeyPair (org.bouncycastle.openssl.PEMKeyPair)35 PKCS8EncryptedPrivateKeyInfo (org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)33 PrivateKeyInfo (com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo)25 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)25 InputDecryptorProvider (org.bouncycastle.operator.InputDecryptorProvider)25 JceOpenSSLPKCS8DecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder)20 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)18 BigInteger (java.math.BigInteger)17 ByteArrayInputStream (java.io.ByteArrayInputStream)16 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)16 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)16 KeyPair (java.security.KeyPair)15 PEMEncryptedKeyPair (org.bouncycastle.openssl.PEMEncryptedKeyPair)15 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)14 InputStreamReader (java.io.InputStreamReader)14