Search in sources :

Example 36 with Attribute

use of com.github.zhenwei.core.asn1.pkcs.Attribute in project LinLong-Java by zhenwei1108.

the class RevocationUtilities method getCRLIssuersFromDistributionPoint.

/**
 * Add the CRL issuers from the cRLIssuer field of the distribution point or from the certificate
 * if not given to the issuer criterion of the
 * <code>selector</code>.
 * <p>
 * The <code>issuerPrincipals</code> are a collection with a single
 * <code>X500Name</code> for <code>X509Certificate</code>s.
 * </p>
 *
 * @param dp               The distribution point.
 * @param issuerPrincipals The issuers of the certificate or attribute certificate which contains
 *                         the distribution point.
 * @param selector         The CRL selector.
 * @throws AnnotatedException if an exception occurs while processing.
 * @throws ClassCastException if <code>issuerPrincipals</code> does not contain only
 *                            <code>X500Name</code>s.
 */
protected static void getCRLIssuersFromDistributionPoint(DistributionPoint dp, Collection issuerPrincipals, X509CRLSelector selector) throws AnnotatedException {
    List issuers = new ArrayList();
    // indirect CRL
    if (dp.getCRLIssuer() != null) {
        GeneralName[] genNames = dp.getCRLIssuer().getNames();
        // look for a DN
        for (int j = 0; j < genNames.length; j++) {
            if (genNames[j].getTagNo() == GeneralName.directoryName) {
                try {
                    issuers.add(X500Name.getInstance(genNames[j].getName()));
                } catch (IllegalArgumentException e) {
                    throw new AnnotatedException("CRL issuer information from distribution point cannot be decoded.", e);
                }
            }
        }
    } else {
        /*
       * certificate issuer is CRL issuer, distributionPoint field MUST be
       * present.
       */
        if (dp.getDistributionPoint() == null) {
            throw new AnnotatedException("CRL issuer is omitted from distribution point but no distributionPoint field present.");
        }
        // add and check issuer principals
        for (Iterator it = issuerPrincipals.iterator(); it.hasNext(); ) {
            issuers.add(it.next());
        }
    }
    // TODO: is not found although this should correctly add the rel name. selector of Sun is buggy here or PKI test case is invalid
    // distributionPoint
    // if (dp.getDistributionPoint() != null)
    // {
    // // look for nameRelativeToCRLIssuer
    // if (dp.getDistributionPoint().getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER)
    // {
    // // append fragment to issuer, only one
    // // issuer can be there, if this is given
    // if (issuers.size() != 1)
    // {
    // throw new AnnotatedException(
    // "nameRelativeToCRLIssuer field is given but more than one CRL issuer is given.");
    // }
    // ASN1Encodable relName = dp.getDistributionPoint().getName();
    // Iterator it = issuers.iterator();
    // List issuersTemp = new ArrayList(issuers.size());
    // while (it.hasNext())
    // {
    // Enumeration e = null;
    // try
    // {
    // e = ASN1Sequence.getInstance(
    // new ASN1InputStream(((X500Principal) it.next())
    // .getEncoded()).readObject()).getObjects();
    // }
    // catch (IOException ex)
    // {
    // throw new AnnotatedException(
    // "Cannot decode CRL issuer information.", ex);
    // }
    // ASN1EncodableVector v = new ASN1EncodableVector();
    // while (e.hasMoreElements())
    // {
    // v.add((ASN1Encodable) e.nextElement());
    // }
    // v.add(relName);
    // issuersTemp.add(new X500Principal(new DERSequence(v)
    // .getDEREncoded()));
    // }
    // issuers.clear();
    // issuers.addAll(issuersTemp);
    // }
    // }
    Iterator it = issuers.iterator();
    while (it.hasNext()) {
        try {
            selector.addIssuerName(((X500Name) it.next()).getEncoded());
        } catch (IOException ex) {
            throw new AnnotatedException("Cannot decode CRL issuer information.", ex);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) GeneralName(com.github.zhenwei.core.asn1.x509.GeneralName) IOException(java.io.IOException) IssuingDistributionPoint(com.github.zhenwei.core.asn1.x509.IssuingDistributionPoint) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint)

Example 37 with Attribute

use of com.github.zhenwei.core.asn1.pkcs.Attribute in project LinLong-Java by zhenwei1108.

the class PKCS12KeyStoreSpi method engineLoad.

public void engineLoad(InputStream stream, char[] password) throws IOException {
    if (// just initialising
    stream == null) {
        return;
    }
    BufferedInputStream bufIn = new BufferedInputStream(stream);
    bufIn.mark(10);
    int head = bufIn.read();
    if (head < 0) {
        throw new EOFException("no data in keystore stream");
    }
    if (head != 0x30) {
        throw new IOException("stream does not represent a PKCS12 key store");
    }
    bufIn.reset();
    ASN1InputStream bIn = new ASN1InputStream(bufIn);
    Pfx bag;
    try {
        bag = Pfx.getInstance(bIn.readObject());
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
    ContentInfo info = bag.getAuthSafe();
    Vector chain = new Vector();
    boolean unmarkedKey = false;
    boolean wrongPKCS12Zero = false;
    if (// check the mac code
    bag.getMacData() != null) {
        if (password == null) {
            throw new NullPointerException("no password supplied when one expected");
        }
        MacData mData = bag.getMacData();
        DigestInfo dInfo = mData.getMac();
        macAlgorithm = dInfo.getAlgorithmId();
        byte[] salt = mData.getSalt();
        itCount = validateIterationCount(mData.getIterationCount());
        saltLength = salt.length;
        byte[] data = ((ASN1OctetString) info.getContent()).getOctets();
        try {
            byte[] res = calculatePbeMac(macAlgorithm.getAlgorithm(), salt, itCount, password, false, data);
            byte[] dig = dInfo.getDigest();
            if (!Arrays.constantTimeAreEqual(res, dig)) {
                if (password.length > 0) {
                    throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file.");
                }
                // Try with incorrect zero length password
                res = calculatePbeMac(macAlgorithm.getAlgorithm(), salt, itCount, password, true, data);
                if (!Arrays.constantTimeAreEqual(res, dig)) {
                    throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file.");
                }
                wrongPKCS12Zero = true;
            }
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw new IOException("error constructing MAC: " + e.toString());
        }
    } else if (password != null && password.length != 0) {
        if (!Properties.isOverrideSet("com.github.zhenwei.pkix.pkcs12.ignore_useless_passwd")) {
            throw new IOException("password supplied for keystore that does not require one");
        }
    }
    keys = new IgnoresCaseHashtable();
    localIds = new IgnoresCaseHashtable();
    if (info.getContentType().equals(data)) {
        ASN1OctetString content = ASN1OctetString.getInstance(info.getContent());
        AuthenticatedSafe authSafe = AuthenticatedSafe.getInstance(content.getOctets());
        ContentInfo[] c = authSafe.getContentInfo();
        for (int i = 0; i != c.length; i++) {
            if (c[i].getContentType().equals(data)) {
                ASN1OctetString authSafeContent = ASN1OctetString.getInstance(c[i].getContent());
                ASN1Sequence seq = ASN1Sequence.getInstance(authSafeContent.getOctets());
                for (int j = 0; j != seq.size(); j++) {
                    SafeBag b = SafeBag.getInstance(seq.getObjectAt(j));
                    if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
                        com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo eIn = com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(b.getBagValue());
                        PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero);
                        // 
                        // set the attributes on the key
                        // 
                        String alias = null;
                        ASN1OctetString localId = null;
                        if (b.getBagAttributes() != null) {
                            Enumeration e = b.getBagAttributes().getObjects();
                            while (e.hasMoreElements()) {
                                ASN1Sequence sq = (ASN1Sequence) e.nextElement();
                                ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier) sq.getObjectAt(0);
                                ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
                                ASN1Primitive attr = null;
                                if (attrSet.size() > 0) {
                                    attr = (ASN1Primitive) attrSet.getObjectAt(0);
                                    if (privKey instanceof PKCS12BagAttributeCarrier) {
                                        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
                                        ASN1Encodable existing = bagAttr.getBagAttribute(aOid);
                                        if (existing != null) {
                                            // OK, but the value has to be the same
                                            if (!existing.toASN1Primitive().equals(attr)) {
                                                throw new IOException("attempt to add existing attribute with different value");
                                            }
                                        } else {
                                            bagAttr.setBagAttribute(aOid, attr);
                                        }
                                    }
                                }
                                if (aOid.equals(pkcs_9_at_friendlyName)) {
                                    alias = ((ASN1BMPString) attr).getString();
                                    keys.put(alias, privKey);
                                } else if (aOid.equals(pkcs_9_at_localKeyId)) {
                                    localId = (ASN1OctetString) attr;
                                }
                            }
                        }
                        if (localId != null) {
                            String name = new String(Hex.encode(localId.getOctets()));
                            if (alias == null) {
                                keys.put(name, privKey);
                            } else {
                                localIds.put(alias, name);
                            }
                        } else {
                            unmarkedKey = true;
                            keys.put("unmarked", privKey);
                        }
                    } else if (b.getBagId().equals(certBag)) {
                        chain.addElement(b);
                    } else {
                        System.out.println("extra in data " + b.getBagId());
                        System.out.println(ASN1Dump.dumpAsString(b));
                    }
                }
            } else if (c[i].getContentType().equals(encryptedData)) {
                EncryptedData d = EncryptedData.getInstance(c[i].getContent());
                byte[] octets = cryptData(false, d.getEncryptionAlgorithm(), password, wrongPKCS12Zero, d.getContent().getOctets());
                ASN1Sequence seq = ASN1Sequence.getInstance(octets);
                for (int j = 0; j != seq.size(); j++) {
                    SafeBag b = SafeBag.getInstance(seq.getObjectAt(j));
                    if (b.getBagId().equals(certBag)) {
                        chain.addElement(b);
                    } else if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
                        com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo eIn = com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(b.getBagValue());
                        PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero);
                        // 
                        // set the attributes on the key
                        // 
                        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
                        String alias = null;
                        ASN1OctetString localId = null;
                        Enumeration e = b.getBagAttributes().getObjects();
                        while (e.hasMoreElements()) {
                            ASN1Sequence sq = (ASN1Sequence) e.nextElement();
                            ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier) sq.getObjectAt(0);
                            ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
                            ASN1Primitive attr = null;
                            if (attrSet.size() > 0) {
                                attr = (ASN1Primitive) attrSet.getObjectAt(0);
                                ASN1Encodable existing = bagAttr.getBagAttribute(aOid);
                                if (existing != null) {
                                    // OK, but the value has to be the same
                                    if (!existing.toASN1Primitive().equals(attr)) {
                                        throw new IOException("attempt to add existing attribute with different value");
                                    }
                                } else {
                                    bagAttr.setBagAttribute(aOid, attr);
                                }
                            }
                            if (aOid.equals(pkcs_9_at_friendlyName)) {
                                alias = ((ASN1BMPString) attr).getString();
                                keys.put(alias, privKey);
                            } else if (aOid.equals(pkcs_9_at_localKeyId)) {
                                localId = (ASN1OctetString) attr;
                            }
                        }
                        String name = new String(Hex.encode(localId.getOctets()));
                        if (alias == null) {
                            keys.put(name, privKey);
                        } else {
                            localIds.put(alias, name);
                        }
                    } else if (b.getBagId().equals(keyBag)) {
                        com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo kInfo = com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo.getInstance(b.getBagValue());
                        PrivateKey privKey = WeGooProvider.getPrivateKey(kInfo);
                        // 
                        // set the attributes on the key
                        // 
                        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
                        String alias = null;
                        ASN1OctetString localId = null;
                        Enumeration e = b.getBagAttributes().getObjects();
                        while (e.hasMoreElements()) {
                            ASN1Sequence sq = ASN1Sequence.getInstance(e.nextElement());
                            ASN1ObjectIdentifier aOid = ASN1ObjectIdentifier.getInstance(sq.getObjectAt(0));
                            ASN1Set attrSet = ASN1Set.getInstance(sq.getObjectAt(1));
                            ASN1Primitive attr = null;
                            if (attrSet.size() > 0) {
                                attr = (ASN1Primitive) attrSet.getObjectAt(0);
                                ASN1Encodable existing = bagAttr.getBagAttribute(aOid);
                                if (existing != null) {
                                    // OK, but the value has to be the same
                                    if (!existing.toASN1Primitive().equals(attr)) {
                                        throw new IOException("attempt to add existing attribute with different value");
                                    }
                                } else {
                                    bagAttr.setBagAttribute(aOid, attr);
                                }
                                if (aOid.equals(pkcs_9_at_friendlyName)) {
                                    alias = ((ASN1BMPString) attr).getString();
                                    keys.put(alias, privKey);
                                } else if (aOid.equals(pkcs_9_at_localKeyId)) {
                                    localId = (ASN1OctetString) attr;
                                }
                            }
                        }
                        String name = new String(Hex.encode(localId.getOctets()));
                        if (alias == null) {
                            keys.put(name, privKey);
                        } else {
                            localIds.put(alias, name);
                        }
                    } else {
                        System.out.println("extra in encryptedData " + b.getBagId());
                        System.out.println(ASN1Dump.dumpAsString(b));
                    }
                }
            } else {
                System.out.println("extra " + c[i].getContentType().getId());
                System.out.println("extra " + ASN1Dump.dumpAsString(c[i].getContent()));
            }
        }
    }
    certs = new IgnoresCaseHashtable();
    chainCerts = new Hashtable();
    keyCerts = new Hashtable();
    for (int i = 0; i != chain.size(); i++) {
        SafeBag b = (SafeBag) chain.elementAt(i);
        CertBag cb = CertBag.getInstance(b.getBagValue());
        if (!cb.getCertId().equals(x509Certificate)) {
            throw new RuntimeException("Unsupported certificate type: " + cb.getCertId());
        }
        Certificate cert;
        try {
            ByteArrayInputStream cIn = new ByteArrayInputStream(((ASN1OctetString) cb.getCertValue()).getOctets());
            cert = certFact.generateCertificate(cIn);
        } catch (Exception e) {
            throw new RuntimeException(e.toString());
        }
        // 
        // set the attributes
        // 
        ASN1OctetString localId = null;
        String alias = null;
        if (b.getBagAttributes() != null) {
            Enumeration e = b.getBagAttributes().getObjects();
            while (e.hasMoreElements()) {
                ASN1Sequence sq = ASN1Sequence.getInstance(e.nextElement());
                ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(sq.getObjectAt(0));
                ASN1Set attrSet = ASN1Set.getInstance(sq.getObjectAt(1));
                if (// sometimes this is empty!
                attrSet.size() > 0) {
                    ASN1Primitive attr = (ASN1Primitive) attrSet.getObjectAt(0);
                    PKCS12BagAttributeCarrier bagAttr = null;
                    if (cert instanceof PKCS12BagAttributeCarrier) {
                        bagAttr = (PKCS12BagAttributeCarrier) cert;
                        ASN1Encodable existing = bagAttr.getBagAttribute(oid);
                        if (existing != null) {
                            // we've found more than one - one might be incorrect
                            if (oid.equals(pkcs_9_at_localKeyId)) {
                                String id = Hex.toHexString(((ASN1OctetString) attr).getOctets());
                                if (!(keys.keys.containsKey(id) || localIds.keys.containsKey(id))) {
                                    // ignore this one - it's not valid
                                    continue;
                                }
                            }
                            // OK, but the value has to be the same
                            if (!existing.toASN1Primitive().equals(attr)) {
                                throw new IOException("attempt to add existing attribute with different value");
                            }
                        } else {
                            bagAttr.setBagAttribute(oid, attr);
                        }
                    }
                    if (oid.equals(pkcs_9_at_friendlyName)) {
                        alias = ((ASN1BMPString) attr).getString();
                    } else if (oid.equals(pkcs_9_at_localKeyId)) {
                        localId = (ASN1OctetString) attr;
                    }
                }
            }
        }
        chainCerts.put(new CertId(cert.getPublicKey()), cert);
        if (unmarkedKey) {
            if (keyCerts.isEmpty()) {
                String name = new String(Hex.encode(createSubjectKeyId(cert.getPublicKey()).getKeyIdentifier()));
                keyCerts.put(name, cert);
                keys.put(name, keys.remove("unmarked"));
            }
        } else {
            // 
            if (localId != null) {
                String name = new String(Hex.encode(localId.getOctets()));
                keyCerts.put(name, cert);
            }
            if (alias != null) {
                certs.put(alias, cert);
            }
        }
    }
}
Also used : ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) PrivateKey(java.security.PrivateKey) ASN1BMPString(com.github.zhenwei.core.asn1.ASN1BMPString) AuthenticatedSafe(com.github.zhenwei.core.asn1.pkcs.AuthenticatedSafe) BEROctetString(com.github.zhenwei.core.asn1.BEROctetString) DERBMPString(com.github.zhenwei.core.asn1.DERBMPString) ASN1BMPString(com.github.zhenwei.core.asn1.ASN1BMPString) ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString) PKCS12BagAttributeCarrier(com.github.zhenwei.provider.jce.interfaces.PKCS12BagAttributeCarrier) BufferedInputStream(java.io.BufferedInputStream) ContentInfo(com.github.zhenwei.core.asn1.pkcs.ContentInfo) EOFException(java.io.EOFException) ASN1Encodable(com.github.zhenwei.core.asn1.ASN1Encodable) EncryptedData(com.github.zhenwei.core.asn1.pkcs.EncryptedData) Vector(java.util.Vector) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) MacData(com.github.zhenwei.core.asn1.pkcs.MacData) ASN1InputStream(com.github.zhenwei.core.asn1.ASN1InputStream) Pfx(com.github.zhenwei.core.asn1.pkcs.Pfx) Enumeration(java.util.Enumeration) Hashtable(java.util.Hashtable) IOException(java.io.IOException) SafeBag(com.github.zhenwei.core.asn1.pkcs.SafeBag) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) IOException(java.io.IOException) EOFException(java.io.EOFException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) CertBag(com.github.zhenwei.core.asn1.pkcs.CertBag) ASN1Set(com.github.zhenwei.core.asn1.ASN1Set) ByteArrayInputStream(java.io.ByteArrayInputStream) DigestInfo(com.github.zhenwei.core.asn1.x509.DigestInfo) ASN1Primitive(com.github.zhenwei.core.asn1.ASN1Primitive) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 38 with Attribute

use of com.github.zhenwei.core.asn1.pkcs.Attribute in project LinLong-Java by zhenwei1108.

the class RFC3280CertPathUtilities method processCRLF.

/**
 * Obtain and validate the certification path for the complete CRL issuer. If a key usage
 * extension is present in the CRL issuer's certificate, verify that the cRLSign bit is set.
 *
 * @param crl                CRL which contains revocation information for the certificate
 *                           <code>cert</code>.
 * @param cert               The attribute certificate or certificate to check if it is revoked.
 * @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>.
 * @param defaultCRLSignKey  The public key of the issuer certificate
 *                           <code>defaultCRLSignCert</code>.
 * @param paramsPKIX         paramsPKIX PKIX parameters.
 * @param certPathCerts      The certificates on the certification path.
 * @return A <code>Set</code> with all keys of possible CRL issuer certificates.
 * @throws AnnotatedException if the CRL is not valid or the status cannot be checked or some
 *                            error occurs.
 */
protected static Set processCRLF(X509CRL crl, Object cert, X509Certificate defaultCRLSignCert, PublicKey defaultCRLSignKey, PKIXExtendedParameters paramsPKIX, List certPathCerts, JcaJceHelper helper) throws AnnotatedException {
    // (f)
    // get issuer from CRL
    X509CertSelector certSelector = new X509CertSelector();
    try {
        byte[] issuerPrincipal = PrincipalUtils.getIssuerPrincipal(crl).getEncoded();
        certSelector.setSubject(issuerPrincipal);
    } catch (IOException e) {
        throw new AnnotatedException("Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e);
    }
    PKIXCertStoreSelector selector = new PKIXCertStoreSelector.Builder(certSelector).build();
    // get CRL signing certs
    LinkedHashSet coll = new LinkedHashSet();
    try {
        CertPathValidatorUtilities.findCertificates(coll, selector, paramsPKIX.getCertificateStores());
        CertPathValidatorUtilities.findCertificates(coll, selector, paramsPKIX.getCertStores());
    } catch (AnnotatedException e) {
        throw new AnnotatedException("Issuer certificate for CRL cannot be searched.", e);
    }
    coll.add(defaultCRLSignCert);
    Iterator cert_it = coll.iterator();
    List validCerts = new ArrayList();
    List validKeys = new ArrayList();
    while (cert_it.hasNext()) {
        X509Certificate signingCert = (X509Certificate) cert_it.next();
        /*
       * CA of the certificate, for which this CRL is checked, has also
       * signed CRL, so skip the path validation, because is already done
       */
        if (signingCert.equals(defaultCRLSignCert)) {
            validCerts.add(signingCert);
            validKeys.add(defaultCRLSignKey);
            continue;
        }
        try {
            CertPathBuilderSpi builder = (revChkClass != null) ? new PKIXCertPathBuilderSpi_8(true) : new PKIXCertPathBuilderSpi(true);
            X509CertSelector tmpCertSelector = new X509CertSelector();
            tmpCertSelector.setCertificate(signingCert);
            PKIXExtendedParameters.Builder paramsBuilder = new PKIXExtendedParameters.Builder(paramsPKIX).setTargetConstraints(new PKIXCertStoreSelector.Builder(tmpCertSelector).build());
            /*
         * if signingCert is placed not higher on the cert path a
         * dependency loop results. CRL for cert is checked, but
         * signingCert is needed for checking the CRL which is dependent
         * on checking cert because it is higher in the cert path and so
         * signing signingCert transitively. so, revocation is disabled,
         * forgery attacks of the CRL are detected in this outer loop
         * for all other it must be enabled to prevent forgery attacks
         */
            if (certPathCerts.contains(signingCert)) {
                paramsBuilder.setRevocationEnabled(false);
            } else {
                paramsBuilder.setRevocationEnabled(true);
            }
            PKIXExtendedBuilderParameters extParams = new PKIXExtendedBuilderParameters.Builder(paramsBuilder.build()).build();
            List certs = builder.engineBuild(extParams).getCertPath().getCertificates();
            validCerts.add(signingCert);
            validKeys.add(CertPathValidatorUtilities.getNextWorkingKey(certs, 0, helper));
        } catch (CertPathBuilderException e) {
            throw new AnnotatedException("CertPath for CRL signer failed to validate.", e);
        } catch (CertPathValidatorException e) {
            throw new AnnotatedException("Public key of issuer certificate of CRL could not be retrieved.", e);
        } catch (Exception e) {
            throw new AnnotatedException(e.getMessage());
        }
    }
    Set checkKeys = new HashSet();
    AnnotatedException lastException = null;
    for (int i = 0; i < validCerts.size(); i++) {
        X509Certificate signCert = (X509Certificate) validCerts.get(i);
        boolean[] keyUsage = signCert.getKeyUsage();
        if (keyUsage != null && (keyUsage.length <= CRL_SIGN || !keyUsage[CRL_SIGN])) {
            lastException = new AnnotatedException("Issuer certificate key usage extension does not permit CRL signing.");
        } else {
            checkKeys.add(validKeys.get(i));
        }
    }
    if (checkKeys.isEmpty() && lastException == null) {
        throw new AnnotatedException("Cannot find a valid issuer certificate.");
    }
    if (checkKeys.isEmpty() && lastException != null) {
        throw lastException;
    }
    return checkKeys;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) ArrayList(java.util.ArrayList) X509CertSelector(java.security.cert.X509CertSelector) PKIXExtendedBuilderParameters(com.github.zhenwei.provider.jcajce.PKIXExtendedBuilderParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException) IssuingDistributionPoint(com.github.zhenwei.core.asn1.x509.IssuingDistributionPoint) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint) CertPathBuilderSpi(java.security.cert.CertPathBuilderSpi) PKIXCertStoreSelector(com.github.zhenwei.provider.jcajce.PKIXCertStoreSelector) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) PKIXExtendedParameters(com.github.zhenwei.provider.jcajce.PKIXExtendedParameters)

Example 39 with Attribute

use of com.github.zhenwei.core.asn1.pkcs.Attribute in project LinLong-Java by zhenwei1108.

the class RFC3281CertPathUtilities method processAttrCert1.

/**
 * Searches for a holder public key certificate and verifies its certification path.
 *
 * @param attrCert   the attribute certificate.
 * @param pkixParams The PKIX parameters.
 * @return The certificate path of the holder certificate.
 * @throws AnnotatedException if
 *                            <ul>
 *                            <li>no public key certificate can be found although holder
 *                            information is given by an entity name or a base certificate
 *                            ID
 *                            <li>support classes cannot be created
 *                            <li>no certification path for the public key certificate can
 *                            be built
 *                            </ul>
 */
protected static CertPath processAttrCert1(X509AttributeCertificate attrCert, PKIXExtendedParameters pkixParams) throws CertPathValidatorException {
    CertPathBuilderResult result = null;
    // find holder PKCs
    LinkedHashSet holderPKCs = new LinkedHashSet();
    if (attrCert.getHolder().getIssuer() != null) {
        X509CertSelector selector = new X509CertSelector();
        selector.setSerialNumber(attrCert.getHolder().getSerialNumber());
        Principal[] principals = attrCert.getHolder().getIssuer();
        for (int i = 0; i < principals.length; i++) {
            try {
                if (principals[i] instanceof X500Principal) {
                    selector.setIssuer(((X500Principal) principals[i]).getEncoded());
                }
                PKIXCertStoreSelector certSelect = new PKIXCertStoreSelector.Builder(selector).build();
                CertPathValidatorUtilities.findCertificates(holderPKCs, certSelect, pkixParams.getCertStores());
            } catch (AnnotatedException e) {
                throw new ExtCertPathValidatorException("Public key certificate for attribute certificate cannot be searched.", e);
            } catch (IOException e) {
                throw new ExtCertPathValidatorException("Unable to encode X500 principal.", e);
            }
        }
        if (holderPKCs.isEmpty()) {
            throw new CertPathValidatorException("Public key certificate specified in base certificate ID for attribute certificate cannot be found.");
        }
    }
    if (attrCert.getHolder().getEntityNames() != null) {
        X509CertStoreSelector selector = new X509CertStoreSelector();
        Principal[] principals = attrCert.getHolder().getEntityNames();
        for (int i = 0; i < principals.length; i++) {
            try {
                if (principals[i] instanceof X500Principal) {
                    selector.setIssuer(((X500Principal) principals[i]).getEncoded());
                }
                PKIXCertStoreSelector certSelect = new PKIXCertStoreSelector.Builder(selector).build();
                CertPathValidatorUtilities.findCertificates(holderPKCs, certSelect, pkixParams.getCertStores());
            } catch (AnnotatedException e) {
                throw new ExtCertPathValidatorException("Public key certificate for attribute certificate cannot be searched.", e);
            } catch (IOException e) {
                throw new ExtCertPathValidatorException("Unable to encode X500 principal.", e);
            }
        }
        if (holderPKCs.isEmpty()) {
            throw new CertPathValidatorException("Public key certificate specified in entity name for attribute certificate cannot be found.");
        }
    }
    // verify cert paths for PKCs
    PKIXExtendedParameters.Builder paramsBldr = new PKIXExtendedParameters.Builder(pkixParams);
    CertPathValidatorException lastException = null;
    for (Iterator it = holderPKCs.iterator(); it.hasNext(); ) {
        X509CertStoreSelector selector = new X509CertStoreSelector();
        selector.setCertificate((X509Certificate) it.next());
        paramsBldr.setTargetConstraints(new PKIXCertStoreSelector.Builder(selector).build());
        CertPathBuilder builder = null;
        try {
            builder = CertPathBuilder.getInstance("PKIX", WeGooProvider.PROVIDER_NAME);
        } catch (NoSuchProviderException e) {
            throw new ExtCertPathValidatorException("Support class could not be created.", e);
        } catch (NoSuchAlgorithmException e) {
            throw new ExtCertPathValidatorException("Support class could not be created.", e);
        }
        try {
            result = builder.build(new PKIXExtendedBuilderParameters.Builder(paramsBldr.build()).build());
        } catch (CertPathBuilderException e) {
            lastException = new ExtCertPathValidatorException("Certification path for public key certificate of attribute certificate could not be build.", e);
        } catch (InvalidAlgorithmParameterException e) {
            // must be a programming error
            throw new RuntimeException(e.getMessage());
        }
    }
    if (lastException != null) {
        throw lastException;
    }
    return result.getCertPath();
}
Also used : LinkedHashSet(java.util.LinkedHashSet) CertPathBuilderResult(java.security.cert.CertPathBuilderResult) CertPathBuilder(java.security.cert.CertPathBuilder) X509CertSelector(java.security.cert.X509CertSelector) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) PKIXExtendedBuilderParameters(com.github.zhenwei.provider.jcajce.PKIXExtendedBuilderParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) Iterator(java.util.Iterator) CertPathBuilder(java.security.cert.CertPathBuilder) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) X509CertStoreSelector(com.github.zhenwei.provider.x509.X509CertStoreSelector) IOException(java.io.IOException) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) PKIXCertStoreSelector(com.github.zhenwei.provider.jcajce.PKIXCertStoreSelector) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) PKIXExtendedParameters(com.github.zhenwei.provider.jcajce.PKIXExtendedParameters) X500Principal(javax.security.auth.x500.X500Principal) NoSuchProviderException(java.security.NoSuchProviderException) X500Principal(javax.security.auth.x500.X500Principal) Principal(java.security.Principal)

Example 40 with Attribute

use of com.github.zhenwei.core.asn1.pkcs.Attribute in project LinLong-Java by zhenwei1108.

the class RFC3281CertPathUtilities method checkCRLs.

/**
 * Checks if an attribute certificate is revoked.
 *
 * @param attrCert      Attribute certificate to check if it is revoked.
 * @param paramsPKIX    PKIX parameters.
 * @param validityDate  The date when the certificate revocation status should be checked.
 * @param issuerCert    The issuer certificate of the attribute certificate
 *                      <code>attrCert</code>.
 * @param certPathCerts The certificates of the certification path to be checked.
 * @throws CertPathValidatorException if the certificate is revoked or the status cannot be
 *                                    checked or some error occurs.
 */
protected static void checkCRLs(X509AttributeCertificate attrCert, PKIXExtendedParameters paramsPKIX, Date currentDate, Date validityDate, X509Certificate issuerCert, List certPathCerts, JcaJceHelper helper) throws CertPathValidatorException {
    if (paramsPKIX.isRevocationEnabled()) {
        // check if revocation is available
        if (attrCert.getExtensionValue(NO_REV_AVAIL) == null) {
            CRLDistPoint crldp = null;
            try {
                crldp = CRLDistPoint.getInstance(CertPathValidatorUtilities.getExtensionValue(attrCert, CRL_DISTRIBUTION_POINTS));
            } catch (AnnotatedException e) {
                throw new CertPathValidatorException("CRL distribution point extension could not be read.", e);
            }
            List crlStores = new ArrayList();
            try {
                crlStores.addAll(CertPathValidatorUtilities.getAdditionalStoresFromCRLDistributionPoint(crldp, paramsPKIX.getNamedCRLStoreMap(), validityDate, helper));
            } catch (AnnotatedException e) {
                throw new CertPathValidatorException("No additional CRL locations could be decoded from CRL distribution point extension.", e);
            }
            PKIXExtendedParameters.Builder bldr = new PKIXExtendedParameters.Builder(paramsPKIX);
            for (Iterator it = crlStores.iterator(); it.hasNext(); ) {
                bldr.addCRLStore((PKIXCRLStore) crlStores);
            }
            paramsPKIX = bldr.build();
            CertStatus certStatus = new CertStatus();
            ReasonsMask reasonsMask = new ReasonsMask();
            AnnotatedException lastException = null;
            boolean validCrlFound = false;
            // for each distribution point
            if (crldp != null) {
                DistributionPoint[] dps = null;
                try {
                    dps = crldp.getDistributionPoints();
                } catch (Exception e) {
                    throw new ExtCertPathValidatorException("Distribution points could not be read.", e);
                }
                try {
                    for (int i = 0; i < dps.length && certStatus.getCertStatus() == CertStatus.UNREVOKED && !reasonsMask.isAllReasons(); i++) {
                        PKIXExtendedParameters paramsPKIXClone = (PKIXExtendedParameters) paramsPKIX.clone();
                        checkCRL(dps[i], attrCert, paramsPKIXClone, currentDate, validityDate, issuerCert, certStatus, reasonsMask, certPathCerts, helper);
                        validCrlFound = true;
                    }
                } catch (AnnotatedException e) {
                    lastException = new AnnotatedException("No valid CRL for distribution point found.", e);
                }
            }
            if (certStatus.getCertStatus() == CertStatus.UNREVOKED && !reasonsMask.isAllReasons()) {
                try {
                    /*
             * assume a DP with both the reasons and the cRLIssuer
             * fields omitted and a distribution point name of the
             * certificate issuer.
             */
                    X500Name issuer;
                    try {
                        issuer = PrincipalUtils.getEncodedIssuerPrincipal(attrCert);
                    } catch (Exception e) {
                        throw new AnnotatedException("Issuer from certificate for CRL could not be reencoded.", e);
                    }
                    DistributionPoint dp = new DistributionPoint(new DistributionPointName(0, new GeneralNames(new GeneralName(GeneralName.directoryName, issuer))), null, null);
                    PKIXExtendedParameters paramsPKIXClone = (PKIXExtendedParameters) paramsPKIX.clone();
                    checkCRL(dp, attrCert, paramsPKIXClone, currentDate, validityDate, issuerCert, certStatus, reasonsMask, certPathCerts, helper);
                    validCrlFound = true;
                } catch (AnnotatedException e) {
                    lastException = new AnnotatedException("No valid CRL for distribution point found.", e);
                }
            }
            if (!validCrlFound) {
                throw new ExtCertPathValidatorException("No valid CRL found.", lastException);
            }
            if (certStatus.getCertStatus() != CertStatus.UNREVOKED) {
                String message = "Attribute certificate revocation after " + certStatus.getRevocationDate();
                message += ", reason: " + RFC3280CertPathUtilities.crlReasons[certStatus.getCertStatus()];
                throw new CertPathValidatorException(message);
            }
            if (!reasonsMask.isAllReasons() && certStatus.getCertStatus() == CertStatus.UNREVOKED) {
                certStatus.setCertStatus(CertStatus.UNDETERMINED);
            }
            if (certStatus.getCertStatus() == CertStatus.UNDETERMINED) {
                throw new CertPathValidatorException("Attribute certificate status could not be determined.");
            }
        } else {
            if (attrCert.getExtensionValue(CRL_DISTRIBUTION_POINTS) != null || attrCert.getExtensionValue(AUTHORITY_INFO_ACCESS) != null) {
                throw new CertPathValidatorException("No rev avail extension is set, but also an AC revocation pointer.");
            }
        }
    }
}
Also used : CertPathBuilder(java.security.cert.CertPathBuilder) ArrayList(java.util.ArrayList) DistributionPointName(com.github.zhenwei.core.asn1.x509.DistributionPointName) X500Name(com.github.zhenwei.core.asn1.x500.X500Name) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CertPathBuilderException(java.security.cert.CertPathBuilderException) CertPathValidatorException(java.security.cert.CertPathValidatorException) IOException(java.io.IOException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) PKIXExtendedParameters(com.github.zhenwei.provider.jcajce.PKIXExtendedParameters) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) GeneralNames(com.github.zhenwei.core.asn1.x509.GeneralNames) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint) GeneralName(com.github.zhenwei.core.asn1.x509.GeneralName) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint)

Aggregations

Attribute (org.bouncycastle.asn1.pkcs.Attribute)36 IOException (java.io.IOException)25 Extensions (org.bouncycastle.asn1.x509.Extensions)18 ArrayList (java.util.ArrayList)17 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)15 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)13 List (java.util.List)12 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)12 GeneralName (org.bouncycastle.asn1.x509.GeneralName)12 ASN1Set (org.bouncycastle.asn1.ASN1Set)10 ASN1Set (com.github.zhenwei.core.asn1.ASN1Set)9 Iterator (java.util.Iterator)9 CRLDistPoint (com.github.zhenwei.core.asn1.x509.CRLDistPoint)8 DistributionPoint (com.github.zhenwei.core.asn1.x509.DistributionPoint)8 AttributeTable (com.github.zhenwei.pkix.util.asn1.cms.AttributeTable)8 Enumeration (java.util.Enumeration)8 X500Name (org.bouncycastle.asn1.x500.X500Name)8 Attribute (com.github.zhenwei.pkix.util.asn1.cms.Attribute)7 GeneralName (com.github.zhenwei.core.asn1.x509.GeneralName)6 GeneralSecurityException (java.security.GeneralSecurityException)6