Search in sources :

Example 21 with AlgorithmIdentifier

use of org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier in project robovm by robovm.

the class PKIXCertPathValidatorSpi method engineValidate.

// END android-added
public CertPathValidatorResult engineValidate(CertPath certPath, CertPathParameters params) throws CertPathValidatorException, InvalidAlgorithmParameterException {
    if (!(params instanceof PKIXParameters)) {
        throw new InvalidAlgorithmParameterException("Parameters must be a " + PKIXParameters.class.getName() + " instance.");
    }
    ExtendedPKIXParameters paramsPKIX;
    if (params instanceof ExtendedPKIXParameters) {
        paramsPKIX = (ExtendedPKIXParameters) params;
    } else {
        paramsPKIX = ExtendedPKIXParameters.getInstance((PKIXParameters) params);
    }
    if (paramsPKIX.getTrustAnchors() == null) {
        throw new InvalidAlgorithmParameterException("trustAnchors is null, this is not allowed for certification path validation.");
    }
    //
    // 6.1.1 - inputs
    //
    //
    // (a)
    //
    List certs = certPath.getCertificates();
    int n = certs.size();
    if (certs.isEmpty()) {
        throw new CertPathValidatorException("Certification path is empty.", null, certPath, 0);
    }
    // BEGIN android-added
    {
        X509Certificate cert = (X509Certificate) certs.get(0);
        if (cert != null) {
            BigInteger serial = cert.getSerialNumber();
            if (blacklist.isSerialNumberBlackListed(serial)) {
                // emulate CRL exception message in RFC3280CertPathUtilities.checkCRLs
                String message = "Certificate revocation of serial 0x" + serial.toString(16);
                System.out.println(message);
                AnnotatedException e = new AnnotatedException(message);
                throw new CertPathValidatorException(e.getMessage(), e, certPath, 0);
            }
        }
    }
    // END android-added
    //
    // (b)
    //
    // Date validDate = CertPathValidatorUtilities.getValidDate(paramsPKIX);
    //
    // (c)
    //
    Set userInitialPolicySet = paramsPKIX.getInitialPolicies();
    //
    // (d)
    // 
    TrustAnchor trust;
    try {
        trust = CertPathValidatorUtilities.findTrustAnchor((X509Certificate) certs.get(certs.size() - 1), paramsPKIX.getTrustAnchors(), paramsPKIX.getSigProvider());
    } catch (AnnotatedException e) {
        throw new CertPathValidatorException(e.getMessage(), e, certPath, certs.size() - 1);
    }
    if (trust == null) {
        throw new CertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1);
    }
    //
    // (e), (f), (g) are part of the paramsPKIX object.
    //
    Iterator certIter;
    int index = 0;
    int i;
    // Certificate for each interation of the validation loop
    // Signature information for each iteration of the validation loop
    //
    // 6.1.2 - setup
    //
    //
    // (a)
    //
    List[] policyNodes = new ArrayList[n + 1];
    for (int j = 0; j < policyNodes.length; j++) {
        policyNodes[j] = new ArrayList();
    }
    Set policySet = new HashSet();
    policySet.add(RFC3280CertPathUtilities.ANY_POLICY);
    PKIXPolicyNode validPolicyTree = new PKIXPolicyNode(new ArrayList(), 0, policySet, null, new HashSet(), RFC3280CertPathUtilities.ANY_POLICY, false);
    policyNodes[0].add(validPolicyTree);
    //
    // (b) and (c)
    //
    PKIXNameConstraintValidator nameConstraintValidator = new PKIXNameConstraintValidator();
    // (d)
    //
    int explicitPolicy;
    Set acceptablePolicies = new HashSet();
    if (paramsPKIX.isExplicitPolicyRequired()) {
        explicitPolicy = 0;
    } else {
        explicitPolicy = n + 1;
    }
    //
    // (e)
    //
    int inhibitAnyPolicy;
    if (paramsPKIX.isAnyPolicyInhibited()) {
        inhibitAnyPolicy = 0;
    } else {
        inhibitAnyPolicy = n + 1;
    }
    //
    // (f)
    //
    int policyMapping;
    if (paramsPKIX.isPolicyMappingInhibited()) {
        policyMapping = 0;
    } else {
        policyMapping = n + 1;
    }
    //
    // (g), (h), (i), (j)
    //
    PublicKey workingPublicKey;
    X500Principal workingIssuerName;
    X509Certificate sign = trust.getTrustedCert();
    try {
        if (sign != null) {
            workingIssuerName = CertPathValidatorUtilities.getSubjectPrincipal(sign);
            workingPublicKey = sign.getPublicKey();
        } else {
            workingIssuerName = new X500Principal(trust.getCAName());
            workingPublicKey = trust.getCAPublicKey();
        }
    } catch (IllegalArgumentException ex) {
        throw new ExtCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", ex, certPath, -1);
    }
    AlgorithmIdentifier workingAlgId = null;
    try {
        workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey);
    } catch (CertPathValidatorException e) {
        throw new ExtCertPathValidatorException("Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1);
    }
    DERObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.getObjectId();
    ASN1Encodable workingPublicKeyParameters = workingAlgId.getParameters();
    //
    // (k)
    //
    int maxPathLength = n;
    if (paramsPKIX.getTargetConstraints() != null && !paramsPKIX.getTargetConstraints().match((X509Certificate) certs.get(0))) {
        throw new ExtCertPathValidatorException("Target certificate in certification path does not match targetConstraints.", null, certPath, 0);
    }
    // 
    // initialize CertPathChecker's
    //
    List pathCheckers = paramsPKIX.getCertPathCheckers();
    certIter = pathCheckers.iterator();
    while (certIter.hasNext()) {
        ((PKIXCertPathChecker) certIter.next()).init(false);
    }
    X509Certificate cert = null;
    for (index = certs.size() - 1; index >= 0; index--) {
        // BEGIN android-added
        if (blacklist.isPublicKeyBlackListed(workingPublicKey)) {
            // emulate CRL exception message in RFC3280CertPathUtilities.checkCRLs
            String message = "Certificate revocation of public key " + workingPublicKey;
            System.out.println(message);
            AnnotatedException e = new AnnotatedException(message);
            throw new CertPathValidatorException(e.getMessage(), e, certPath, index);
        }
        // END android-added
        // try
        // {
        //
        // i as defined in the algorithm description
        //
        i = n - index;
        //
        // set certificate to be checked in this round
        // sign and workingPublicKey and workingIssuerName are set
        // at the end of the for loop and initialized the
        // first time from the TrustAnchor
        //
        cert = (X509Certificate) certs.get(index);
        boolean verificationAlreadyPerformed = (index == certs.size() - 1);
        //
        // 6.1.3
        //
        RFC3280CertPathUtilities.processCertA(certPath, paramsPKIX, index, workingPublicKey, verificationAlreadyPerformed, workingIssuerName, sign);
        RFC3280CertPathUtilities.processCertBC(certPath, index, nameConstraintValidator);
        validPolicyTree = RFC3280CertPathUtilities.processCertD(certPath, index, acceptablePolicies, validPolicyTree, policyNodes, inhibitAnyPolicy);
        validPolicyTree = RFC3280CertPathUtilities.processCertE(certPath, index, validPolicyTree);
        RFC3280CertPathUtilities.processCertF(certPath, index, validPolicyTree, explicitPolicy);
        if (i != n) {
            if (cert != null && cert.getVersion() == 1) {
                throw new CertPathValidatorException("Version 1 certificates can't be used as CA ones.", null, certPath, index);
            }
            RFC3280CertPathUtilities.prepareNextCertA(certPath, index);
            validPolicyTree = RFC3280CertPathUtilities.prepareCertB(certPath, index, policyNodes, validPolicyTree, policyMapping);
            RFC3280CertPathUtilities.prepareNextCertG(certPath, index, nameConstraintValidator);
            // (h)
            explicitPolicy = RFC3280CertPathUtilities.prepareNextCertH1(certPath, index, explicitPolicy);
            policyMapping = RFC3280CertPathUtilities.prepareNextCertH2(certPath, index, policyMapping);
            inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertH3(certPath, index, inhibitAnyPolicy);
            //
            // (i)
            //
            explicitPolicy = RFC3280CertPathUtilities.prepareNextCertI1(certPath, index, explicitPolicy);
            policyMapping = RFC3280CertPathUtilities.prepareNextCertI2(certPath, index, policyMapping);
            // (j)
            inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertJ(certPath, index, inhibitAnyPolicy);
            // (k)
            RFC3280CertPathUtilities.prepareNextCertK(certPath, index);
            // (l)
            maxPathLength = RFC3280CertPathUtilities.prepareNextCertL(certPath, index, maxPathLength);
            // (m)
            maxPathLength = RFC3280CertPathUtilities.prepareNextCertM(certPath, index, maxPathLength);
            // (n)
            RFC3280CertPathUtilities.prepareNextCertN(certPath, index);
            Set criticalExtensions = cert.getCriticalExtensionOIDs();
            if (criticalExtensions != null) {
                criticalExtensions = new HashSet(criticalExtensions);
                // these extensions are handled by the algorithm
                criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE);
                criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
                criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS);
                criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY);
                criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
                criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
                criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS);
                criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS);
                criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME);
                criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS);
            } else {
                criticalExtensions = new HashSet();
            }
            // (o)
            RFC3280CertPathUtilities.prepareNextCertO(certPath, index, criticalExtensions, pathCheckers);
            // set signing certificate for next round
            sign = cert;
            // (c)
            workingIssuerName = CertPathValidatorUtilities.getSubjectPrincipal(sign);
            // (d)
            try {
                workingPublicKey = CertPathValidatorUtilities.getNextWorkingKey(certPath.getCertificates(), index);
            } catch (CertPathValidatorException e) {
                throw new CertPathValidatorException("Next working key could not be retrieved.", e, certPath, index);
            }
            workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey);
            // (f)
            workingPublicKeyAlgorithm = workingAlgId.getObjectId();
            // (e)
            workingPublicKeyParameters = workingAlgId.getParameters();
        }
    }
    //
    // 6.1.5 Wrap-up procedure
    //
    explicitPolicy = RFC3280CertPathUtilities.wrapupCertA(explicitPolicy, cert);
    explicitPolicy = RFC3280CertPathUtilities.wrapupCertB(certPath, index + 1, explicitPolicy);
    //
    // (c) (d) and (e) are already done
    //
    //
    // (f)
    //
    Set criticalExtensions = cert.getCriticalExtensionOIDs();
    if (criticalExtensions != null) {
        criticalExtensions = new HashSet(criticalExtensions);
        // these extensions are handled by the algorithm
        criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE);
        criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
        criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS);
        criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY);
        criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
        criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
        criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS);
        criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS);
        criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME);
        criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS);
        criticalExtensions.remove(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS);
    } else {
        criticalExtensions = new HashSet();
    }
    RFC3280CertPathUtilities.wrapupCertF(certPath, index + 1, pathCheckers, criticalExtensions);
    PKIXPolicyNode intersection = RFC3280CertPathUtilities.wrapupCertG(certPath, paramsPKIX, userInitialPolicySet, index + 1, policyNodes, validPolicyTree, acceptablePolicies);
    if ((explicitPolicy > 0) || (intersection != null)) {
        return new PKIXCertPathValidatorResult(trust, intersection, cert.getPublicKey());
    }
    throw new CertPathValidatorException("Path processing failed on policy.", null, certPath, index);
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ArrayList(java.util.ArrayList) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) ExtendedPKIXParameters(org.bouncycastle.x509.ExtendedPKIXParameters) PKIXParameters(java.security.cert.PKIXParameters) PKIXCertPathChecker(java.security.cert.PKIXCertPathChecker) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) HashSet(java.util.HashSet) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PublicKey(java.security.PublicKey) TrustAnchor(java.security.cert.TrustAnchor) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) X509Certificate(java.security.cert.X509Certificate) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) ExtendedPKIXParameters(org.bouncycastle.x509.ExtendedPKIXParameters) PKIXCertPathValidatorResult(java.security.cert.PKIXCertPathValidatorResult) BigInteger(java.math.BigInteger) X500Principal(javax.security.auth.x500.X500Principal)

Example 22 with AlgorithmIdentifier

use of org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier in project robovm by robovm.

the class PKCS12KeyStoreSpi method doStore.

private void doStore(OutputStream stream, char[] password, boolean useDEREncoding) throws IOException {
    if (password == null) {
        throw new NullPointerException("No password supplied for PKCS#12 KeyStore.");
    }
    //
    // handle the key
    //
    ASN1EncodableVector keyS = new ASN1EncodableVector();
    Enumeration ks = keys.keys();
    while (ks.hasMoreElements()) {
        byte[] kSalt = new byte[SALT_SIZE];
        random.nextBytes(kSalt);
        String name = (String) ks.nextElement();
        PrivateKey privKey = (PrivateKey) keys.get(name);
        PKCS12PBEParams kParams = new PKCS12PBEParams(kSalt, MIN_ITERATIONS);
        byte[] kBytes = wrapKey(keyAlgorithm.getId(), privKey, kParams, password);
        AlgorithmIdentifier kAlgId = new AlgorithmIdentifier(keyAlgorithm, kParams.toASN1Primitive());
        org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo kInfo = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo(kAlgId, kBytes);
        boolean attrSet = false;
        ASN1EncodableVector kName = new ASN1EncodableVector();
        if (privKey instanceof PKCS12BagAttributeCarrier) {
            PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) privKey;
            //
            // make sure we are using the local alias on store
            //
            DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
            if (nm == null || !nm.getString().equals(name)) {
                bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name));
            }
            //
            if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) {
                Certificate ct = engineGetCertificate(name);
                bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(ct.getPublicKey()));
            }
            Enumeration e = bagAttrs.getBagAttributeKeys();
            while (e.hasMoreElements()) {
                ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
                ASN1EncodableVector kSeq = new ASN1EncodableVector();
                kSeq.add(oid);
                kSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                attrSet = true;
                kName.add(new DERSequence(kSeq));
            }
        }
        if (!attrSet) {
            //
            // set a default friendly name (from the key id) and local id
            //
            ASN1EncodableVector kSeq = new ASN1EncodableVector();
            Certificate ct = engineGetCertificate(name);
            kSeq.add(pkcs_9_at_localKeyId);
            kSeq.add(new DERSet(createSubjectKeyId(ct.getPublicKey())));
            kName.add(new DERSequence(kSeq));
            kSeq = new ASN1EncodableVector();
            kSeq.add(pkcs_9_at_friendlyName);
            kSeq.add(new DERSet(new DERBMPString(name)));
            kName.add(new DERSequence(kSeq));
        }
        SafeBag kBag = new SafeBag(pkcs8ShroudedKeyBag, kInfo.toASN1Primitive(), new DERSet(kName));
        keyS.add(kBag);
    }
    byte[] keySEncoded = new DERSequence(keyS).getEncoded(ASN1Encoding.DER);
    BEROctetString keyString = new BEROctetString(keySEncoded);
    //
    // certificate processing
    //
    byte[] cSalt = new byte[SALT_SIZE];
    random.nextBytes(cSalt);
    ASN1EncodableVector certSeq = new ASN1EncodableVector();
    PKCS12PBEParams cParams = new PKCS12PBEParams(cSalt, MIN_ITERATIONS);
    AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.toASN1Primitive());
    Hashtable doneCerts = new Hashtable();
    Enumeration cs = keys.keys();
    while (cs.hasMoreElements()) {
        try {
            String name = (String) cs.nextElement();
            Certificate cert = engineGetCertificate(name);
            boolean cAttrSet = false;
            CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
            ASN1EncodableVector fName = new ASN1EncodableVector();
            if (cert instanceof PKCS12BagAttributeCarrier) {
                PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
                //
                // make sure we are using the local alias on store
                //
                DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
                if (nm == null || !nm.getString().equals(name)) {
                    bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name));
                }
                //
                if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) {
                    bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(cert.getPublicKey()));
                }
                Enumeration e = bagAttrs.getBagAttributeKeys();
                while (e.hasMoreElements()) {
                    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
                    ASN1EncodableVector fSeq = new ASN1EncodableVector();
                    fSeq.add(oid);
                    fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                    fName.add(new DERSequence(fSeq));
                    cAttrSet = true;
                }
            }
            if (!cAttrSet) {
                ASN1EncodableVector fSeq = new ASN1EncodableVector();
                fSeq.add(pkcs_9_at_localKeyId);
                fSeq.add(new DERSet(createSubjectKeyId(cert.getPublicKey())));
                fName.add(new DERSequence(fSeq));
                fSeq = new ASN1EncodableVector();
                fSeq.add(pkcs_9_at_friendlyName);
                fSeq.add(new DERSet(new DERBMPString(name)));
                fName.add(new DERSequence(fSeq));
            }
            SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName));
            certSeq.add(sBag);
            doneCerts.put(cert, cert);
        } catch (CertificateEncodingException e) {
            throw new IOException("Error encoding certificate: " + e.toString());
        }
    }
    cs = certs.keys();
    while (cs.hasMoreElements()) {
        try {
            String certId = (String) cs.nextElement();
            Certificate cert = (Certificate) certs.get(certId);
            boolean cAttrSet = false;
            if (keys.get(certId) != null) {
                continue;
            }
            CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
            ASN1EncodableVector fName = new ASN1EncodableVector();
            if (cert instanceof PKCS12BagAttributeCarrier) {
                PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
                //
                // make sure we are using the local alias on store
                //
                DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
                if (nm == null || !nm.getString().equals(certId)) {
                    bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(certId));
                }
                Enumeration e = bagAttrs.getBagAttributeKeys();
                while (e.hasMoreElements()) {
                    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
                    // If we find one, we'll prune it out.
                    if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) {
                        continue;
                    }
                    ASN1EncodableVector fSeq = new ASN1EncodableVector();
                    fSeq.add(oid);
                    fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                    fName.add(new DERSequence(fSeq));
                    cAttrSet = true;
                }
            }
            if (!cAttrSet) {
                ASN1EncodableVector fSeq = new ASN1EncodableVector();
                fSeq.add(pkcs_9_at_friendlyName);
                fSeq.add(new DERSet(new DERBMPString(certId)));
                fName.add(new DERSequence(fSeq));
            }
            SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName));
            certSeq.add(sBag);
            doneCerts.put(cert, cert);
        } catch (CertificateEncodingException e) {
            throw new IOException("Error encoding certificate: " + e.toString());
        }
    }
    cs = chainCerts.keys();
    while (cs.hasMoreElements()) {
        try {
            CertId certId = (CertId) cs.nextElement();
            Certificate cert = (Certificate) chainCerts.get(certId);
            if (doneCerts.get(cert) != null) {
                continue;
            }
            CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
            ASN1EncodableVector fName = new ASN1EncodableVector();
            if (cert instanceof PKCS12BagAttributeCarrier) {
                PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
                Enumeration e = bagAttrs.getBagAttributeKeys();
                while (e.hasMoreElements()) {
                    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
                    // If we find one, we'll prune it out.
                    if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) {
                        continue;
                    }
                    ASN1EncodableVector fSeq = new ASN1EncodableVector();
                    fSeq.add(oid);
                    fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                    fName.add(new DERSequence(fSeq));
                }
            }
            SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName));
            certSeq.add(sBag);
        } catch (CertificateEncodingException e) {
            throw new IOException("Error encoding certificate: " + e.toString());
        }
    }
    byte[] certSeqEncoded = new DERSequence(certSeq).getEncoded(ASN1Encoding.DER);
    byte[] certBytes = cryptData(true, cAlgId, password, false, certSeqEncoded);
    EncryptedData cInfo = new EncryptedData(data, cAlgId, new BEROctetString(certBytes));
    ContentInfo[] info = new ContentInfo[] { new ContentInfo(data, keyString), new ContentInfo(encryptedData, cInfo.toASN1Primitive()) };
    AuthenticatedSafe auth = new AuthenticatedSafe(info);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream asn1Out;
    if (useDEREncoding) {
        asn1Out = new DEROutputStream(bOut);
    } else {
        asn1Out = new BEROutputStream(bOut);
    }
    asn1Out.writeObject(auth);
    byte[] pkg = bOut.toByteArray();
    ContentInfo mainInfo = new ContentInfo(data, new BEROctetString(pkg));
    //
    // create the mac
    //
    byte[] mSalt = new byte[20];
    int itCount = MIN_ITERATIONS;
    random.nextBytes(mSalt);
    byte[] data = ((ASN1OctetString) mainInfo.getContent()).getOctets();
    MacData mData;
    try {
        byte[] res = calculatePbeMac(id_SHA1, mSalt, itCount, password, false, data);
        AlgorithmIdentifier algId = new AlgorithmIdentifier(id_SHA1, DERNull.INSTANCE);
        DigestInfo dInfo = new DigestInfo(algId, res);
        mData = new MacData(dInfo, mSalt, itCount);
    } catch (Exception e) {
        throw new IOException("error constructing MAC: " + e.toString());
    }
    //
    // output the Pfx
    //
    Pfx pfx = new Pfx(mainInfo, mData);
    if (useDEREncoding) {
        asn1Out = new DEROutputStream(stream);
    } else {
        asn1Out = new BEROutputStream(stream);
    }
    asn1Out.writeObject(pfx);
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) PrivateKey(java.security.PrivateKey) AuthenticatedSafe(org.bouncycastle.asn1.pkcs.AuthenticatedSafe) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERBMPString(org.bouncycastle.asn1.DERBMPString) DEROctetString(org.bouncycastle.asn1.DEROctetString) BEROctetString(org.bouncycastle.asn1.BEROctetString) DERSet(org.bouncycastle.asn1.DERSet) PKCS12BagAttributeCarrier(org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERSequence(org.bouncycastle.asn1.DERSequence) BEROctetString(org.bouncycastle.asn1.BEROctetString) ContentInfo(org.bouncycastle.asn1.pkcs.ContentInfo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) EncryptedData(org.bouncycastle.asn1.pkcs.EncryptedData) MacData(org.bouncycastle.asn1.pkcs.MacData) Enumeration(java.util.Enumeration) DERBMPString(org.bouncycastle.asn1.DERBMPString) Pfx(org.bouncycastle.asn1.pkcs.Pfx) Hashtable(java.util.Hashtable) BEROutputStream(org.bouncycastle.asn1.BEROutputStream) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SafeBag(org.bouncycastle.asn1.pkcs.SafeBag) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) CertBag(org.bouncycastle.asn1.pkcs.CertBag) PKCS12PBEParams(org.bouncycastle.asn1.pkcs.PKCS12PBEParams) DigestInfo(org.bouncycastle.asn1.x509.DigestInfo) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) DEROutputStream(org.bouncycastle.asn1.DEROutputStream)

Example 23 with AlgorithmIdentifier

use of org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier in project robovm by robovm.

the class CertPathValidatorUtilities method getAlgorithmIdentifier.

protected static AlgorithmIdentifier getAlgorithmIdentifier(PublicKey key) throws CertPathValidatorException {
    try {
        ASN1InputStream aIn = new ASN1InputStream(key.getEncoded());
        SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject());
        return info.getAlgorithmId();
    } catch (Exception e) {
        throw new ExtCertPathValidatorException("Subject public key cannot be decoded.", e);
    }
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ParseException(java.text.ParseException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertStoreException(java.security.cert.CertStoreException) CRLException(java.security.cert.CRLException) CertificateParsingException(java.security.cert.CertificateParsingException) StoreException(org.bouncycastle.util.StoreException) IOException(java.io.IOException)

Example 24 with AlgorithmIdentifier

use of org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier in project ambry by linkedin.

the class TestSSLUtils method generateCertificate.

/**
 * Create a self-signed X.509 Certificate.
 * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
 *
 * @param dn the X.509 Distinguished Name, eg "CN(commonName)=Test, O(organizationName)=Org"
 * @param pair the KeyPair
 * @param days how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 * @throws java.security.cert.CertificateException thrown if a security error or an IO error ocurred.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) throws CertificateException {
    try {
        Security.addProvider(new BouncyCastleProvider());
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
        ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
        X500Name name = new X500Name(dn);
        Date from = new Date();
        Date to = new Date(from.getTime() + days * 86400000L);
        BigInteger sn = new BigInteger(64, new SecureRandom());
        X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
        X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
    } catch (CertificateException ce) {
        throw ce;
    } catch (Exception e) {
        throw new CertificateException(e);
    }
}
Also used : ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) EOFException(java.io.EOFException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) X509v1CertificateBuilder(org.bouncycastle.cert.X509v1CertificateBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 25 with AlgorithmIdentifier

use of org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier in project android by nextcloud.

the class CsrHelper method generateCSR.

/**
 * Create the certificate signing request (CSR) from private and public keys
 *
 * @param keyPair the KeyPair with private and public keys
 * @param userId userId of CSR owner
 * @return PKCS10CertificationRequest with the certificate signing request (CSR) data
 * @throws IOException thrown if key cannot be created
 * @throws OperatorCreationException thrown if contentSigner cannot be build
 */
private static PKCS10CertificationRequest generateCSR(KeyPair keyPair, String userId) throws IOException, OperatorCreationException {
    String principal = "CN=" + userId;
    AsymmetricKeyParameter privateKey = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
    AlgorithmIdentifier signatureAlgorithm = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WITHRSA");
    AlgorithmIdentifier digestAlgorithm = new DefaultDigestAlgorithmIdentifierFinder().find("SHA-1");
    ContentSigner signer = new BcRSAContentSignerBuilder(signatureAlgorithm, digestAlgorithm).build(privateKey);
    PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(new X500Name(principal), keyPair.getPublic());
    ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
    extensionsGenerator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
    csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate());
    return csrBuilder.build(signer);
}
Also used : BcRSAContentSignerBuilder(org.spongycastle.operator.bc.BcRSAContentSignerBuilder) JcaPKCS10CertificationRequestBuilder(org.spongycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) AsymmetricKeyParameter(org.spongycastle.crypto.params.AsymmetricKeyParameter) ContentSigner(org.spongycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.spongycastle.pkcs.PKCS10CertificationRequestBuilder) JcaPKCS10CertificationRequestBuilder(org.spongycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) X500Name(org.spongycastle.asn1.x500.X500Name) DefaultDigestAlgorithmIdentifierFinder(org.spongycastle.operator.DefaultDigestAlgorithmIdentifierFinder) BasicConstraints(org.spongycastle.asn1.x509.BasicConstraints) AlgorithmIdentifier(org.spongycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.spongycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) ExtensionsGenerator(org.spongycastle.asn1.x509.ExtensionsGenerator)

Aggregations

AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)111 IOException (java.io.IOException)47 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)35 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)35 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)32 BigInteger (java.math.BigInteger)29 X509Certificate (java.security.cert.X509Certificate)27 X500Name (org.bouncycastle.asn1.x500.X500Name)27 DEROctetString (org.bouncycastle.asn1.DEROctetString)21 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)20 KeyPair (java.security.KeyPair)19 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)19 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)19 Date (java.util.Date)18 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)18 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)17 DERSequence (org.bouncycastle.asn1.DERSequence)16 KeyPairGenerator (java.security.KeyPairGenerator)15 PublicKey (java.security.PublicKey)14 InvalidKeyException (java.security.InvalidKeyException)13