Search in sources :

Example 31 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo 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(org.eclipse.jdt.annotation.Nullable)

Example 32 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project certmgr by hdecarne.

the class PKCS12CertReaderWriter method readBinary.

@Override
@Nullable
public CertObjectStore readBinary(IOResource<InputStream> in, PasswordCallback password) throws IOException {
    LOG.debug("Trying to read PKCS#12 objects from: ''{0}''...", in);
    CertObjectStore certObjects = null;
    PKCS12PfxPdu pkcs12 = readPKCS12(in);
    if (pkcs12 != null) {
        certObjects = new CertObjectStore();
        for (ContentInfo contentInfo : pkcs12.getContentInfos()) {
            ASN1ObjectIdentifier contentType = contentInfo.getContentType();
            PKCS12SafeBagFactory safeBagFactory;
            if (contentType.equals(PKCSObjectIdentifiers.encryptedData)) {
                safeBagFactory = getSafeBagFactory(contentInfo, in.resource(), password);
            } else {
                safeBagFactory = getSafeBagFactory(contentInfo);
            }
            for (PKCS12SafeBag safeBag : safeBagFactory.getSafeBags()) {
                Object safeBagValue = safeBag.getBagValue();
                if (safeBagValue instanceof X509CertificateHolder) {
                    certObjects.addCRT(convertCRT((X509CertificateHolder) safeBagValue));
                } else if (safeBagValue instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PrivateKey privateKey = convertPrivateKey((PKCS8EncryptedPrivateKeyInfo) safeBagValue, in.resource(), password);
                    try {
                        certObjects.addKey(KeyHelper.rebuildKeyPair(privateKey));
                    } catch (IOException e) {
                        LOG.warning(e, "Unable to rebuild key pair for private key of type ''{1}''", privateKey.getClass().getName());
                    }
                } else if (safeBagValue instanceof PrivateKeyInfo) {
                    PrivateKey privateKey = convertPrivateKey((PrivateKeyInfo) safeBagValue);
                    try {
                        certObjects.addKey(KeyHelper.rebuildKeyPair(privateKey));
                    } catch (IOException e) {
                        LOG.warning(e, "Unable to rebuild key pair for private key of type ''{1}''", privateKey.getClass().getName());
                    }
                } else {
                    LOG.warning(CertIOI18N.STR_PKCS12_UNKNOWN_OBJECT, safeBagValue.getClass().getName());
                }
            }
        }
    }
    return certObjects;
}
Also used : PrivateKey(java.security.PrivateKey) PKCS12SafeBagFactory(org.bouncycastle.pkcs.PKCS12SafeBagFactory) ContentInfo(org.bouncycastle.asn1.pkcs.ContentInfo) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) CertObjectStore(de.carne.certmgr.certs.CertObjectStore) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) IOException(java.io.IOException) PKCS12SafeBag(org.bouncycastle.pkcs.PKCS12SafeBag) PKCS12PfxPdu(org.bouncycastle.pkcs.PKCS12PfxPdu) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) Nullable(org.eclipse.jdt.annotation.Nullable)

Example 33 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project BiglyBT by BiglySoftware.

the class JCEECPrivateKey method getEncoded.

/**
 * Return a PKCS8 representation of the key. The sequence returned
 * represents a full PrivateKeyInfo object.
 *
 * @return a PKCS8 representation of the key.
 */
@Override
public byte[] getEncoded() {
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    X962Parameters params = null;
    if (ecSpec instanceof ECNamedCurveParameterSpec) {
        params = new X962Parameters(X962NamedCurves.getOID(((ECNamedCurveParameterSpec) ecSpec).getName()));
    } else {
        X9ECParameters ecP = new X9ECParameters(ecSpec.getCurve(), ecSpec.getG(), ecSpec.getN(), ecSpec.getH(), ecSpec.getSeed());
        params = new X962Parameters(ecP);
    }
    PrivateKeyInfo info = new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params.getDERObject()), new ECPrivateKeyStructure(this.getD()).getDERObject());
    try {
        dOut.writeObject(info);
        dOut.close();
    } catch (IOException e) {
        throw new RuntimeException("Error encoding EC private key");
    }
    return bOut.toByteArray();
}
Also used : X962Parameters(org.gudy.bouncycastle.asn1.x9.X962Parameters) X9ECParameters(org.gudy.bouncycastle.asn1.x9.X9ECParameters) ECNamedCurveParameterSpec(org.gudy.bouncycastle.jce.spec.ECNamedCurveParameterSpec) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ECPrivateKeyStructure(org.gudy.bouncycastle.asn1.sec.ECPrivateKeyStructure) IOException(java.io.IOException) PrivateKeyInfo(org.gudy.bouncycastle.asn1.pkcs.PrivateKeyInfo) AlgorithmIdentifier(org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 34 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project X-Road by nordic-institute.

the class CertUtils method readKeyPairFromPemFile.

/**
 * Read private and public keys from PEM file
 * @param filename file containing the keypair
 * @return KeyPair
 * @throws NoSuchAlgorithmException when algorithm for decoding is not available
 * @throws InvalidKeySpecException when key file is invalid
 * @throws IOException when I/O error occurs
 */
public static KeyPair readKeyPairFromPemFile(String filename) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
    File pkFile = new File(filename);
    try (PEMParser pemParser = new PEMParser(new FileReader(pkFile))) {
        Object o = pemParser.readObject();
        if (o == null || !(o instanceof PrivateKeyInfo)) {
            throw new CodedException(X_INTERNAL_ERROR, "Could not read key from '%s'", filename);
        }
        PrivateKeyInfo pki = (PrivateKeyInfo) o;
        KeyFactory kf = KeyFactory.getInstance("RSA");
        final PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(pki.getEncoded());
        final PrivateKey privateKey = kf.generatePrivate(ks);
        final RSAPrivateKey rpk = RSAPrivateKey.getInstance(pki.parsePrivateKey());
        final PublicKey publicKey = kf.generatePublic(new RSAPublicKeySpec(rpk.getModulus(), rpk.getPublicExponent()));
        KeyPair kp = new KeyPair(publicKey, privateKey);
        return kp;
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) RSAPrivateKey(org.bouncycastle.asn1.pkcs.RSAPrivateKey) PublicKey(java.security.PublicKey) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) PEMParser(org.bouncycastle.openssl.PEMParser) CodedException(ee.ria.xroad.common.CodedException) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) FileReader(java.io.FileReader) CryptoUtils.toDERObject(ee.ria.xroad.common.util.CryptoUtils.toDERObject) File(java.io.File) RSAPrivateKey(org.bouncycastle.asn1.pkcs.RSAPrivateKey) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) KeyFactory(java.security.KeyFactory)

Example 35 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project sshj by hierynomus.

the class PKCS8KeyFile method readKeyPair.

protected KeyPair readKeyPair() throws IOException {
    KeyPair kp = null;
    for (PEMParser r = null; ; ) {
        // while the PasswordFinder tells us we should retry
        try {
            r = new PEMParser(resource.getReader());
            final Object o = r.readObject();
            final JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
            if (SecurityUtils.getSecurityProvider() != null) {
                pemConverter.setProvider(SecurityUtils.getSecurityProvider());
            }
            if (o instanceof PEMEncryptedKeyPair) {
                final PEMEncryptedKeyPair encryptedKeyPair = (PEMEncryptedKeyPair) o;
                final PEMKeyPair pemKeyPair = readEncryptedKeyPair(encryptedKeyPair);
                kp = pemConverter.getKeyPair(pemKeyPair);
            } else if (o instanceof PEMKeyPair) {
                kp = pemConverter.getKeyPair((PEMKeyPair) o);
            } else if (o instanceof PrivateKeyInfo) {
                final PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) o;
                final PEMKeyPair pemKeyPair = privateKeyInfoKeyPairConverter.getKeyPair(privateKeyInfo);
                kp = pemConverter.getKeyPair(pemKeyPair);
            } else if (o instanceof PKCS8EncryptedPrivateKeyInfo) {
                final PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) o;
                final PrivateKeyInfo privateKeyInfo = readEncryptedPrivateKeyInfo(encryptedPrivateKeyInfo);
                final PEMKeyPair pemKeyPair = privateKeyInfoKeyPairConverter.getKeyPair(privateKeyInfo);
                kp = pemConverter.getKeyPair(pemKeyPair);
            } else {
                log.warn("Unexpected PKCS8 PEM Object [{}]", o);
            }
        } catch (EncryptionException e) {
            if (pwdf != null && pwdf.shouldRetry(resource))
                continue;
            else
                throw new KeyDecryptionFailedException(e);
        } finally {
            IOUtils.closeQuietly(r);
        }
        break;
    }
    if (kp == null)
        throw new IOException("Could not read key pair from: " + resource);
    return kp;
}
Also used : PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) KeyPair(java.security.KeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) KeyDecryptionFailedException(com.hierynomus.sshj.common.KeyDecryptionFailedException) PEMParser(org.bouncycastle.openssl.PEMParser) EncryptionException(org.bouncycastle.openssl.EncryptionException) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) IOException(java.io.IOException) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) 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