Search in sources :

Example 26 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project keystore-explorer by kaikramer.

the class EccUtil method convertToECPrivateKeyStructure.

/**
 * Converts PKCS#8 EC private key (RFC 5208/5958 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:
 * <p>
 * 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 {
    PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(ecPrivateKey.getEncoded());
    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)

Example 27 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 pvkData 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(byte[] pvkData) throws CryptoException, IOException {
    EncryptionType encType = getEncryptionType(pvkData);
    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(pvkData);
    if (pemInfo != null) {
        // It is - get DER from PEM
        pvkData = pemInfo.getContent();
    }
    try (ASN1InputStream asn1InputStream = new ASN1InputStream(pvkData)) {
        // Read OpenSSL DER structure
        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.getParametersObject());
                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) 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 28 with PrivateKeyInfo

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

the class CmpAgent method requestCertificate0.

// method requestCertificate
private EnrollCertResponse requestCertificate0(PKIMessage reqMessage, Map<BigInteger, String> reqIdIdMap, int expectedBodyType, ReqRespDebug debug) throws CmpClientException, PkiErrorException {
    VerifiedPkiMessage response = signAndSend(reqMessage, debug);
    checkProtection(response);
    PKIBody respBody = response.getPkiMessage().getBody();
    final int bodyType = respBody.getType();
    if (PKIBody.TYPE_ERROR == bodyType) {
        ErrorMsgContent content = ErrorMsgContent.getInstance(respBody.getContent());
        throw new PkiErrorException(content.getPKIStatusInfo());
    } else if (expectedBodyType != bodyType) {
        throw new CmpClientException(String.format("unknown PKI body type %s instead the expected [%s, %s]", bodyType, expectedBodyType, PKIBody.TYPE_ERROR));
    }
    CertRepMessage certRep = CertRepMessage.getInstance(respBody.getContent());
    CertResponse[] certResponses = certRep.getResponse();
    EnrollCertResponse result = new EnrollCertResponse();
    // CA certificates
    CMPCertificate[] caPubs = certRep.getCaPubs();
    if (caPubs != null && caPubs.length > 0) {
        for (CMPCertificate caPub : caPubs) {
            if (caPub != null) {
                result.addCaCertificate(caPub);
            }
        }
    }
    CertificateConfirmationContentBuilder certConfirmBuilder = null;
    if (!CmpUtil.isImplictConfirm(response.getPkiMessage().getHeader())) {
        certConfirmBuilder = new CertificateConfirmationContentBuilder();
    }
    boolean requireConfirm = false;
    // We only accept the certificates which are requested.
    for (CertResponse certResp : certResponses) {
        PKIStatusInfo statusInfo = certResp.getStatus();
        int status = statusInfo.getStatus().intValue();
        BigInteger certReqId = certResp.getCertReqId().getValue();
        String thisId = reqIdIdMap.get(certReqId);
        if (thisId != null) {
            reqIdIdMap.remove(certReqId);
        } else if (reqIdIdMap.size() == 1) {
            thisId = reqIdIdMap.values().iterator().next();
            reqIdIdMap.clear();
        }
        if (thisId == null) {
            // ignore it. this cert is not requested by me
            continue;
        }
        ResultEntry resultEntry;
        if (status == PKIStatus.GRANTED || status == PKIStatus.GRANTED_WITH_MODS) {
            CertifiedKeyPair cvk = certResp.getCertifiedKeyPair();
            if (cvk == null) {
                return null;
            }
            CMPCertificate cmpCert = cvk.getCertOrEncCert().getCertificate();
            if (cmpCert == null) {
                return null;
            }
            if (requestor == null) {
                result.addResultEntry(new ResultEntry.Error(thisId, PKISTATUS_RESPONSE_ERROR, PKIFailureInfo.systemFailure, "could not decrypt PrivateKeyInfo/requestor is null"));
                continue;
            }
            PrivateKeyInfo privKeyInfo = null;
            if (cvk.getPrivateKey() != null) {
                // decryp the encrypted private key
                byte[] decryptedValue;
                try {
                    if (requestor instanceof Requestor.SignatureCmpRequestor) {
                        ConcurrentContentSigner requestSigner = ((Requestor.SignatureCmpRequestor) requestor).getSigner();
                        if (!(requestSigner.getSigningKey() instanceof PrivateKey)) {
                            throw new XiSecurityException("no decryption key is configured");
                        }
                        decryptedValue = decrypt(cvk.getPrivateKey(), (PrivateKey) requestSigner.getSigningKey());
                    } else {
                        decryptedValue = decrypt(cvk.getPrivateKey(), ((Requestor.PbmMacCmpRequestor) requestor).getPassword());
                    }
                } catch (XiSecurityException ex) {
                    result.addResultEntry(new ResultEntry.Error(thisId, PKISTATUS_RESPONSE_ERROR, PKIFailureInfo.systemFailure, "could not decrypt PrivateKeyInfo"));
                    continue;
                }
                privKeyInfo = PrivateKeyInfo.getInstance(decryptedValue);
            }
            resultEntry = new ResultEntry.EnrollCert(thisId, cmpCert, privKeyInfo, status);
            if (certConfirmBuilder != null) {
                requireConfirm = true;
                X509CertificateHolder certHolder = new X509CertificateHolder(cmpCert.getX509v3PKCert());
                certConfirmBuilder.addAcceptedCertificate(certHolder, certReqId);
            }
        } else {
            PKIFreeText statusString = statusInfo.getStatusString();
            String errorMessage = (statusString == null) ? null : statusString.getStringAt(0).getString();
            int failureInfo = statusInfo.getFailInfo().intValue();
            resultEntry = new ResultEntry.Error(thisId, status, failureInfo, errorMessage);
        }
        result.addResultEntry(resultEntry);
    }
    if (CollectionUtil.isNotEmpty(reqIdIdMap)) {
        for (Entry<BigInteger, String> entry : reqIdIdMap.entrySet()) {
            result.addResultEntry(new ResultEntry.Error(entry.getValue(), PKISTATUS_NO_ANSWER));
        }
    }
    if (!requireConfirm) {
        return result;
    }
    PKIMessage confirmRequest = buildCertConfirmRequest(response.getPkiMessage().getHeader().getTransactionID(), certConfirmBuilder);
    response = signAndSend(confirmRequest, debug);
    checkProtection(response);
    return result;
}
Also used : PrivateKey(java.security.PrivateKey) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 29 with PrivateKeyInfo

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

the class CmpCaClient method parseEnrollCertResult.

// method transmit
private Map<BigInteger, KeyAndCert> parseEnrollCertResult(PKIMessage response, int resonseBodyType, int numCerts) throws Exception {
    PKIBody respBody = response.getBody();
    final int bodyType = respBody.getType();
    if (PKIBody.TYPE_ERROR == bodyType) {
        ErrorMsgContent content = ErrorMsgContent.getInstance(respBody.getContent());
        throw new Exception("Server returned PKIStatus: " + buildText(content.getPKIStatusInfo()));
    } else if (resonseBodyType != bodyType) {
        throw new Exception(String.format("unknown PKI body type %s instead the expected [%s, %s]", bodyType, resonseBodyType, PKIBody.TYPE_ERROR));
    }
    CertRepMessage certRep = CertRepMessage.getInstance(respBody.getContent());
    CertResponse[] certResponses = certRep.getResponse();
    if (certResponses.length != numCerts) {
        throw new Exception("expected " + numCerts + " CertResponse, but returned " + certResponses.length);
    }
    // We only accept the certificates which are requested.
    Map<BigInteger, KeyAndCert> keycerts = new HashMap<>(numCerts * 2);
    for (int i = 0; i < numCerts; i++) {
        CertResponse certResp = certResponses[i];
        PKIStatusInfo statusInfo = certResp.getStatus();
        int status = statusInfo.getStatus().intValue();
        BigInteger certReqId = certResp.getCertReqId().getValue();
        if (status != PKIStatus.GRANTED && status != PKIStatus.GRANTED_WITH_MODS) {
            throw new Exception("CertReqId " + certReqId + ": server returned PKIStatus: " + buildText(statusInfo));
        }
        CertifiedKeyPair cvk = certResp.getCertifiedKeyPair();
        if (cvk != null) {
            CMPCertificate cmpCert = cvk.getCertOrEncCert().getCertificate();
            X509Certificate cert = SdkUtil.parseCert(cmpCert.getX509v3PKCert().getEncoded());
            if (!verify(caCert, cert)) {
                throw new Exception("CertReqId " + certReqId + ": the returned certificate is not issued by the given CA");
            }
            EncryptedKey encKey = cvk.getPrivateKey();
            PrivateKeyInfo key = null;
            if (encKey != null) {
                byte[] keyBytes = decrypt(encKey);
                key = PrivateKeyInfo.getInstance(keyBytes);
            }
            keycerts.put(certReqId, new KeyAndCert(key, cert));
        }
    }
    return keycerts;
}
Also used : OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) BigInteger(java.math.BigInteger) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 30 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project android_packages_apps_Settings by SudaMod.

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)

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