Search in sources :

Example 41 with KeyUsage

use of com.github.zhenwei.core.asn1.x509.KeyUsage 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 42 with KeyUsage

use of com.github.zhenwei.core.asn1.x509.KeyUsage in project LinLong-Java by zhenwei1108.

the class PKIXCertPathReviewer method checkSignatures.

/*
   * checks: - signatures - name chaining - validity of certificates - todo:
   * if certificate revoked (if specified in the parameters)
   */
private void checkSignatures() {
    // 1.6.1 - Inputs
    // d)
    TrustAnchor trust = null;
    X500Principal trustPrincipal = null;
    // validation date
    {
        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certPathValidDate", new Object[] { new TrustedInput(validDate), new TrustedInput(currentDate) });
        addNotification(msg);
    }
    // find trust anchors
    try {
        X509Certificate cert = (X509Certificate) certs.get(certs.size() - 1);
        Collection trustColl = getTrustAnchors(cert, pkixParams.getTrustAnchors());
        if (trustColl.size() > 1) {
            // conflicting trust anchors
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.conflictingTrustAnchors", new Object[] { Integers.valueOf(trustColl.size()), new UntrustedInput(cert.getIssuerX500Principal()) });
            addError(msg);
        } else if (trustColl.isEmpty()) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noTrustAnchorFound", new Object[] { new UntrustedInput(cert.getIssuerX500Principal()), Integers.valueOf(pkixParams.getTrustAnchors().size()) });
            addError(msg);
        } else {
            PublicKey trustPublicKey;
            trust = (TrustAnchor) trustColl.iterator().next();
            if (trust.getTrustedCert() != null) {
                trustPublicKey = trust.getTrustedCert().getPublicKey();
            } else {
                trustPublicKey = trust.getCAPublicKey();
            }
            try {
                CertPathValidatorUtilities.verifyX509Certificate(cert, trustPublicKey, pkixParams.getSigProvider());
            } catch (SignatureException e) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustButInvalidCert");
                addError(msg);
            } catch (Exception e) {
            // do nothing, error occurs again later
            }
        }
    } catch (CertPathReviewerException cpre) {
        addError(cpre.getErrorMessage());
    } catch (Throwable t) {
        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.unknown", new Object[] { new UntrustedInput(t.getMessage()), new UntrustedInput(t) });
        addError(msg);
    }
    if (trust != null) {
        // get the name of the trustAnchor
        X509Certificate sign = trust.getTrustedCert();
        try {
            if (sign != null) {
                trustPrincipal = getSubjectPrincipal(sign);
            } else {
                trustPrincipal = new X500Principal(trust.getCAName());
            }
        } catch (IllegalArgumentException ex) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustDNInvalid", new Object[] { new UntrustedInput(trust.getCAName()) });
            addError(msg);
        }
        // test key usages of the trust anchor
        if (sign != null) {
            boolean[] ku = sign.getKeyUsage();
            if (ku != null && (ku.length <= 5 || !ku[5])) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustKeyUsage");
                addNotification(msg);
            }
        }
    }
    // 1.6.2 - Initialization
    PublicKey workingPublicKey = null;
    X500Principal workingIssuerName = trustPrincipal;
    X509Certificate sign = null;
    AlgorithmIdentifier workingAlgId = null;
    ASN1ObjectIdentifier workingPublicKeyAlgorithm = null;
    ASN1Encodable workingPublicKeyParameters = null;
    if (trust != null) {
        sign = trust.getTrustedCert();
        if (sign != null) {
            workingPublicKey = sign.getPublicKey();
        } else {
            workingPublicKey = trust.getCAPublicKey();
        }
        try {
            workingAlgId = getAlgorithmIdentifier(workingPublicKey);
            workingPublicKeyAlgorithm = workingAlgId.getAlgorithm();
            workingPublicKeyParameters = workingAlgId.getParameters();
        } catch (CertPathValidatorException ex) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustPubKeyError");
            addError(msg);
            workingAlgId = null;
        }
    }
    // Basic cert checks
    X509Certificate cert = null;
    int i;
    for (int index = certs.size() - 1; index >= 0; index--) {
        // 
        // 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 initialied the
        // first time from the TrustAnchor
        // 
        cert = (X509Certificate) certs.get(index);
        // verify signature
        if (workingPublicKey != null) {
            try {
                CertPathValidatorUtilities.verifyX509Certificate(cert, workingPublicKey, pkixParams.getSigProvider());
            } catch (GeneralSecurityException ex) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.signatureNotVerified", new Object[] { ex.getMessage(), ex, ex.getClass().getName() });
                addError(msg, index);
            }
        } else if (isSelfIssued(cert)) {
            try {
                CertPathValidatorUtilities.verifyX509Certificate(cert, cert.getPublicKey(), pkixParams.getSigProvider());
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.rootKeyIsValidButNotATrustAnchor");
                addError(msg, index);
            } catch (GeneralSecurityException ex) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.signatureNotVerified", new Object[] { ex.getMessage(), ex, ex.getClass().getName() });
                addError(msg, index);
            }
        } else {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.NoIssuerPublicKey");
            // if there is an authority key extension add the serial and issuer of the missing certificate
            byte[] akiBytes = cert.getExtensionValue(Extension.authorityKeyIdentifier.getId());
            if (akiBytes != null) {
                AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.getInstance(DEROctetString.getInstance(akiBytes).getOctets());
                GeneralNames issuerNames = aki.getAuthorityCertIssuer();
                if (issuerNames != null) {
                    GeneralName name = issuerNames.getNames()[0];
                    BigInteger serial = aki.getAuthorityCertSerialNumber();
                    if (serial != null) {
                        Object[] extraArgs = { new LocaleString(RESOURCE_NAME, "missingIssuer"), " \"", name, "\" ", new LocaleString(RESOURCE_NAME, "missingSerial"), " ", serial };
                        msg.setExtraArguments(extraArgs);
                    }
                }
            }
            addError(msg, index);
        }
        // certificate valid?
        try {
            cert.checkValidity(validDate);
        } catch (CertificateNotYetValidException cnve) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certificateNotYetValid", new Object[] { new TrustedInput(cert.getNotBefore()) });
            addError(msg, index);
        } catch (CertificateExpiredException cee) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certificateExpired", new Object[] { new TrustedInput(cert.getNotAfter()) });
            addError(msg, index);
        }
        // certificate revoked?
        if (pkixParams.isRevocationEnabled()) {
            // read crl distribution points extension
            CRLDistPoint crlDistPoints = null;
            try {
                ASN1Primitive crl_dp = getExtensionValue(cert, CRL_DIST_POINTS);
                if (crl_dp != null) {
                    crlDistPoints = CRLDistPoint.getInstance(crl_dp);
                }
            } catch (AnnotatedException ae) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlDistPtExtError");
                addError(msg, index);
            }
            // read authority information access extension
            AuthorityInformationAccess authInfoAcc = null;
            try {
                ASN1Primitive auth_info_acc = getExtensionValue(cert, AUTH_INFO_ACCESS);
                if (auth_info_acc != null) {
                    authInfoAcc = AuthorityInformationAccess.getInstance(auth_info_acc);
                }
            } catch (AnnotatedException ae) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlAuthInfoAccError");
                addError(msg, index);
            }
            Vector crlDistPointUrls = getCRLDistUrls(crlDistPoints);
            Vector ocspUrls = getOCSPUrls(authInfoAcc);
            // add notifications with the crl distribution points
            // output crl distribution points
            Iterator urlIt = crlDistPointUrls.iterator();
            while (urlIt.hasNext()) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlDistPoint", new Object[] { new UntrustedUrlInput(urlIt.next()) });
                addNotification(msg, index);
            }
            // output ocsp urls
            urlIt = ocspUrls.iterator();
            while (urlIt.hasNext()) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.ocspLocation", new Object[] { new UntrustedUrlInput(urlIt.next()) });
                addNotification(msg, index);
            }
            // check CRLs
            try {
                checkRevocation(pkixParams, cert, validDate, sign, workingPublicKey, crlDistPointUrls, ocspUrls, index);
            } catch (CertPathReviewerException cpre) {
                addError(cpre.getErrorMessage(), index);
            }
        }
        // certificate issuer correct
        if (workingIssuerName != null && !cert.getIssuerX500Principal().equals(workingIssuerName)) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certWrongIssuer", new Object[] { workingIssuerName.getName(), cert.getIssuerX500Principal().getName() });
            addError(msg, index);
        }
        // 
        if (i != n) {
            if (cert != null && cert.getVersion() == 1) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCACert");
                addError(msg, index);
            }
            // k)
            BasicConstraints bc;
            try {
                bc = BasicConstraints.getInstance(getExtensionValue(cert, BASIC_CONSTRAINTS));
                if (bc != null) {
                    if (!bc.isCA()) {
                        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCACert");
                        addError(msg, index);
                    }
                } else {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noBasicConstraints");
                    addError(msg, index);
                }
            } catch (AnnotatedException ae) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.errorProcesingBC");
                addError(msg, index);
            }
            // n)
            boolean[] keyUsage = cert.getKeyUsage();
            if (keyUsage != null && (keyUsage.length <= KEY_CERT_SIGN || !keyUsage[KEY_CERT_SIGN])) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCertSign");
                addError(msg, index);
            }
        }
        // if
        // set signing certificate for next round
        sign = cert;
        // c)
        workingIssuerName = cert.getSubjectX500Principal();
        try {
            workingPublicKey = getNextWorkingKey(certs, index);
            workingAlgId = getAlgorithmIdentifier(workingPublicKey);
            workingPublicKeyAlgorithm = workingAlgId.getAlgorithm();
            workingPublicKeyParameters = workingAlgId.getParameters();
        } catch (CertPathValidatorException ex) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.pubKeyError");
            addError(msg, index);
            workingAlgId = null;
            workingPublicKeyAlgorithm = null;
            workingPublicKeyParameters = null;
        }
    }
    // for
    trustAnchor = trust;
    subjectPublicKey = workingPublicKey;
}
Also used : AuthorityInformationAccess(com.github.zhenwei.core.asn1.x509.AuthorityInformationAccess) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) AuthorityKeyIdentifier(com.github.zhenwei.core.asn1.x509.AuthorityKeyIdentifier) SignatureException(java.security.SignatureException) UntrustedUrlInput(com.github.zhenwei.core.i18n.filter.UntrustedUrlInput) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) TrustedInput(com.github.zhenwei.core.i18n.filter.TrustedInput) Iterator(java.util.Iterator) ASN1Encodable(com.github.zhenwei.core.asn1.ASN1Encodable) UntrustedInput(com.github.zhenwei.core.i18n.filter.UntrustedInput) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) Vector(java.util.Vector) AnnotatedException(com.github.zhenwei.provider.jce.provider.AnnotatedException) LocaleString(com.github.zhenwei.core.i18n.LocaleString) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) TrustAnchor(java.security.cert.TrustAnchor) X509Certificate(java.security.cert.X509Certificate) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) AnnotatedException(com.github.zhenwei.provider.jce.provider.AnnotatedException) SignatureException(java.security.SignatureException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) PKIXNameConstraintValidatorException(com.github.zhenwei.provider.jce.provider.PKIXNameConstraintValidatorException) 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) CertPathValidatorException(java.security.cert.CertPathValidatorException) ErrorBundle(com.github.zhenwei.core.i18n.ErrorBundle) GeneralNames(com.github.zhenwei.core.asn1.x509.GeneralNames) X500Principal(javax.security.auth.x500.X500Principal) Collection(java.util.Collection) BigInteger(java.math.BigInteger) ASN1TaggedObject(com.github.zhenwei.core.asn1.ASN1TaggedObject) GeneralName(com.github.zhenwei.core.asn1.x509.GeneralName) ASN1Primitive(com.github.zhenwei.core.asn1.ASN1Primitive) BasicConstraints(com.github.zhenwei.core.asn1.x509.BasicConstraints) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)

Example 43 with KeyUsage

use of com.github.zhenwei.core.asn1.x509.KeyUsage in project LinLong-Java by zhenwei1108.

the class PKIXCertPathReviewer method checkCRLs.

protected void checkCRLs(PKIXParameters paramsPKIX, X509Certificate cert, Date validDate, X509Certificate sign, PublicKey workingPublicKey, Vector crlDistPointUrls, int index) throws CertPathReviewerException {
    X509CRLStoreSelector crlselect;
    crlselect = new X509CRLStoreSelector();
    try {
        crlselect.addIssuerName(getEncodedIssuerPrincipal(cert).getEncoded());
    } catch (IOException e) {
        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlIssuerException");
        throw new CertPathReviewerException(msg, e);
    }
    crlselect.setCertificateChecking(cert);
    Iterator crl_iter;
    try {
        Collection crl_coll = PKIXCRLUtil.findCRLs(crlselect, paramsPKIX);
        crl_iter = crl_coll.iterator();
        if (crl_coll.isEmpty()) {
            // notification - no local crls found
            crl_coll = PKIXCRLUtil.findCRLs(new X509CRLStoreSelector(), paramsPKIX);
            Iterator it = crl_coll.iterator();
            List nonMatchingCrlNames = new ArrayList();
            while (it.hasNext()) {
                nonMatchingCrlNames.add(((X509CRL) it.next()).getIssuerX500Principal());
            }
            int numbOfCrls = nonMatchingCrlNames.size();
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCrlInCertstore", new Object[] { new UntrustedInput(crlselect.getIssuerNames()), new UntrustedInput(nonMatchingCrlNames), Integers.valueOf(numbOfCrls) });
            addNotification(msg, index);
        }
    } catch (AnnotatedException ae) {
        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlExtractionError", new Object[] { ae.getCause().getMessage(), ae.getCause(), ae.getCause().getClass().getName() });
        addError(msg, index);
        crl_iter = new ArrayList().iterator();
    }
    boolean validCrlFound = false;
    X509CRL crl = null;
    while (crl_iter.hasNext()) {
        crl = (X509CRL) crl_iter.next();
        Date thisUpdate = crl.getThisUpdate();
        Date nextUpdate = crl.getNextUpdate();
        Object[] arguments = new Object[] { new TrustedInput(thisUpdate), new TrustedInput(nextUpdate) };
        if (nextUpdate == null || validDate.before(nextUpdate)) {
            validCrlFound = true;
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.localValidCRL", arguments);
            addNotification(msg, index);
            break;
        }
        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.localInvalidCRL", arguments);
        addNotification(msg, index);
    }
    // crl distribution point
    if (!validCrlFound) {
        X500Principal certIssuer = cert.getIssuerX500Principal();
        X509CRL onlineCRL = null;
        Iterator urlIt = crlDistPointUrls.iterator();
        while (urlIt.hasNext()) {
            try {
                String location = (String) urlIt.next();
                onlineCRL = getCRL(location);
                if (onlineCRL != null) {
                    X500Principal crlIssuer = onlineCRL.getIssuerX500Principal();
                    // check if crl issuer is correct
                    if (!certIssuer.equals(crlIssuer)) {
                        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.onlineCRLWrongCA", new Object[] { new UntrustedInput(crlIssuer.getName()), new UntrustedInput(certIssuer.getName()), new UntrustedUrlInput(location) });
                        addNotification(msg, index);
                        continue;
                    }
                    Date thisUpdate = onlineCRL.getThisUpdate();
                    Date nextUpdate = onlineCRL.getNextUpdate();
                    Object[] arguments = new Object[] { new TrustedInput(thisUpdate), new TrustedInput(nextUpdate), new UntrustedUrlInput(location) };
                    if (nextUpdate == null || validDate.before(nextUpdate)) {
                        validCrlFound = true;
                        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.onlineValidCRL", arguments);
                        addNotification(msg, index);
                        crl = onlineCRL;
                        break;
                    }
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.onlineInvalidCRL", arguments);
                    addNotification(msg, index);
                }
            } catch (CertPathReviewerException cpre) {
                addNotification(cpre.getErrorMessage(), index);
            }
        }
    }
    // check the crl
    X509CRLEntry crl_entry;
    if (crl != null) {
        if (sign != null) {
            boolean[] keyUsage = sign.getKeyUsage();
            if (keyUsage != null && (keyUsage.length <= CRL_SIGN || !keyUsage[CRL_SIGN])) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCrlSigningPermited");
                throw new CertPathReviewerException(msg);
            }
        }
        if (workingPublicKey != null) {
            try {
                crl.verify(workingPublicKey, "WeGoo");
            } catch (Exception e) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlVerifyFailed");
                throw new CertPathReviewerException(msg, e);
            }
        } else // issuer public key not known
        {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlNoIssuerPublicKey");
            throw new CertPathReviewerException(msg);
        }
        crl_entry = crl.getRevokedCertificate(cert.getSerialNumber());
        if (crl_entry != null) {
            String reason = null;
            if (crl_entry.hasExtensions()) {
                ASN1Enumerated reasonCode;
                try {
                    reasonCode = ASN1Enumerated.getInstance(getExtensionValue(crl_entry, Extension.reasonCode.getId()));
                } catch (AnnotatedException ae) {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlReasonExtError");
                    throw new CertPathReviewerException(msg, ae);
                }
                if (reasonCode != null) {
                    reason = crlReasons[reasonCode.intValueExact()];
                }
            }
            if (reason == null) {
                // unknown
                reason = crlReasons[7];
            }
            // i18n reason
            LocaleString ls = new LocaleString(RESOURCE_NAME, reason);
            if (!validDate.before(crl_entry.getRevocationDate())) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certRevoked", new Object[] { new TrustedInput(crl_entry.getRevocationDate()), ls });
                throw new CertPathReviewerException(msg);
            } else // cert was revoked after validation date
            {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.revokedAfterValidation", new Object[] { new TrustedInput(crl_entry.getRevocationDate()), ls });
                addNotification(msg, index);
            }
        } else // cert is not revoked
        {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.notRevoked");
            addNotification(msg, index);
        }
        // 
        // warn if a new crl is available
        // 
        Date nextUpdate = crl.getNextUpdate();
        if (!(nextUpdate == null || validDate.before(nextUpdate))) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlUpdateAvailable", new Object[] { new TrustedInput(nextUpdate) });
            addNotification(msg, index);
        }
        // 
        // check the DeltaCRL indicator, base point and the issuing distribution point
        // 
        ASN1Primitive idp;
        try {
            idp = getExtensionValue(crl, ISSUING_DISTRIBUTION_POINT);
        } catch (AnnotatedException ae) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.distrPtExtError");
            throw new CertPathReviewerException(msg);
        }
        ASN1Primitive dci;
        try {
            dci = getExtensionValue(crl, DELTA_CRL_INDICATOR);
        } catch (AnnotatedException ae) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.deltaCrlExtError");
            throw new CertPathReviewerException(msg);
        }
        if (dci != null) {
            X509CRLStoreSelector baseSelect = new X509CRLStoreSelector();
            try {
                baseSelect.addIssuerName(getIssuerPrincipal(crl).getEncoded());
            } catch (IOException e) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlIssuerException");
                throw new CertPathReviewerException(msg, e);
            }
            baseSelect.setMinCRLNumber(((ASN1Integer) dci).getPositiveValue());
            try {
                baseSelect.setMaxCRLNumber(((ASN1Integer) getExtensionValue(crl, CRL_NUMBER)).getPositiveValue().subtract(BigInteger.valueOf(1)));
            } catch (AnnotatedException ae) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlNbrExtError");
                throw new CertPathReviewerException(msg, ae);
            }
            boolean foundBase = false;
            Iterator it;
            try {
                it = PKIXCRLUtil.findCRLs(baseSelect, paramsPKIX).iterator();
            } catch (AnnotatedException ae) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlExtractionError");
                throw new CertPathReviewerException(msg, ae);
            }
            while (it.hasNext()) {
                X509CRL base = (X509CRL) it.next();
                ASN1Primitive baseIdp;
                try {
                    baseIdp = getExtensionValue(base, ISSUING_DISTRIBUTION_POINT);
                } catch (AnnotatedException ae) {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.distrPtExtError");
                    throw new CertPathReviewerException(msg, ae);
                }
                if (Objects.areEqual(idp, baseIdp)) {
                    foundBase = true;
                    break;
                }
            }
            if (!foundBase) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noBaseCRL");
                throw new CertPathReviewerException(msg);
            }
        }
        if (idp != null) {
            IssuingDistributionPoint p = IssuingDistributionPoint.getInstance(idp);
            BasicConstraints bc = null;
            try {
                bc = BasicConstraints.getInstance(getExtensionValue(cert, BASIC_CONSTRAINTS));
            } catch (AnnotatedException ae) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlBCExtError");
                throw new CertPathReviewerException(msg, ae);
            }
            if (p.onlyContainsUserCerts() && (bc != null && bc.isCA())) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlOnlyUserCert");
                throw new CertPathReviewerException(msg);
            }
            if (p.onlyContainsCACerts() && (bc == null || !bc.isCA())) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlOnlyCaCert");
                throw new CertPathReviewerException(msg);
            }
            if (p.onlyContainsAttributeCerts()) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlOnlyAttrCert");
                throw new CertPathReviewerException(msg);
            }
        }
    }
    if (!validCrlFound) {
        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noValidCrlFound");
        throw new CertPathReviewerException(msg);
    }
}
Also used : X509CRL(java.security.cert.X509CRL) IssuingDistributionPoint(com.github.zhenwei.core.asn1.x509.IssuingDistributionPoint) ArrayList(java.util.ArrayList) ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString) LocaleString(com.github.zhenwei.core.i18n.LocaleString) ASN1IA5String(com.github.zhenwei.core.asn1.ASN1IA5String) UntrustedUrlInput(com.github.zhenwei.core.i18n.filter.UntrustedUrlInput) X509CRLEntry(java.security.cert.X509CRLEntry) ASN1Enumerated(com.github.zhenwei.core.asn1.ASN1Enumerated) Iterator(java.util.Iterator) TrustedInput(com.github.zhenwei.core.i18n.filter.TrustedInput) List(java.util.List) ArrayList(java.util.ArrayList) UntrustedInput(com.github.zhenwei.core.i18n.filter.UntrustedInput) AnnotatedException(com.github.zhenwei.provider.jce.provider.AnnotatedException) LocaleString(com.github.zhenwei.core.i18n.LocaleString) IOException(java.io.IOException) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer) IssuingDistributionPoint(com.github.zhenwei.core.asn1.x509.IssuingDistributionPoint) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint) Date(java.util.Date) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) AnnotatedException(com.github.zhenwei.provider.jce.provider.AnnotatedException) SignatureException(java.security.SignatureException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) PKIXNameConstraintValidatorException(com.github.zhenwei.provider.jce.provider.PKIXNameConstraintValidatorException) IOException(java.io.IOException) ErrorBundle(com.github.zhenwei.core.i18n.ErrorBundle) Collection(java.util.Collection) X500Principal(javax.security.auth.x500.X500Principal) ASN1TaggedObject(com.github.zhenwei.core.asn1.ASN1TaggedObject) ASN1Primitive(com.github.zhenwei.core.asn1.ASN1Primitive) BasicConstraints(com.github.zhenwei.core.asn1.x509.BasicConstraints)

Example 44 with KeyUsage

use of com.github.zhenwei.core.asn1.x509.KeyUsage in project LinLong-Java by zhenwei1108.

the class CertBuilder method generateCertificate.

/**
 * @param [dn, publicKey, privateKey]
 * @return java.security.cert.Certificate
 * @author zhangzhenwei
 * @description 生成证书
 * todo just support sm2
 * @date 2022/3/15  9:09 下午
 * @since: 1.0.0
 */
public static byte[] generateCertificate(String subjectDn, String issuerDn, PublicKey publicKey, PrivateKey privateKey, SignAlgEnum signAlgEnum, int time, TimeUnit timeUnit) throws WeGooCryptoException {
    try {
        SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        // SubjectPublicKeyInfo publicKeyInfo = (SubjectPublicKeyInfo)publicKey;
        X500Name subject = new X500Name(subjectDn);
        X500Name issuer = new X500Name(issuerDn);
        byte[] bytes = new byte[15];
        Random random = new Random();
        random.nextBytes(bytes);
        byte[] bytes1 = ByteArrayUtil.mergeBytes("9".getBytes(StandardCharsets.UTF_8), bytes);
        BigInteger sn = new BigInteger(bytes1);
        Date notBefore = DateUtil.now();
        int max = Math.max(1, (int) timeUnit.toDays(time));
        Date notAfter = DateUtil.nowPlusDays(max);
        BcX509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
        // 密钥用途:  签名和不可抵赖
        int usage = KeyUsage.digitalSignature | KeyUsage.nonRepudiation;
        // 使用者标识符
        SubjectKeyIdentifier subjectKeyIdentifier = x509ExtensionUtils.createSubjectKeyIdentifier(publicKeyInfo);
        // 授权者标识符
        AuthorityKeyIdentifier authorityKeyIdentifier = x509ExtensionUtils.createAuthorityKeyIdentifier(publicKeyInfo);
        // 判断是否签发根证书
        if (subject.toString().equals(subject.toString())) {
            // 根证书 颁发者标识符
            authorityKeyIdentifier = x509ExtensionUtils.createAuthorityKeyIdentifier(publicKeyInfo);
            // 补充证书签名用途
            usage = usage | KeyUsage.keyCertSign;
        }
        X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuer, sn, notBefore, notAfter, subject, publicKeyInfo);
        // 增加扩展项
        Extension keyUsage = new Extension(Extension.keyUsage, false, new KeyUsage(usage).getEncoded());
        Extension subjectKeyId = new Extension(Extension.subjectKeyIdentifier, false, subjectKeyIdentifier.getEncoded());
        Extension authorityKeyId = new Extension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier.getEncoded());
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(signAlgEnum.getOid());
        AlgorithmIdentifier digAlgId = new AlgorithmIdentifier(signAlgEnum.getDigestAlgEnum().getOid());
        builder.addExtension(keyUsage);
        builder.addExtension(subjectKeyId);
        builder.addExtension(authorityKeyId);
        X509CertificateHolder holder;
        BcContentSignerBuilder signerBuilder;
        AsymmetricKeyParameter keyParameters;
        if (publicKey.getAlgorithm().equals("EC")) {
            signerBuilder = new BcECContentSignerBuilder(sigAlgId, digAlgId);
            BCECPrivateKey key = (BCECPrivateKey) privateKey;
            ECParameterSpec parameters = key.getParameters();
            ECDomainParameters params = new ECDomainParameters(parameters.getCurve(), parameters.getG(), parameters.getN());
            keyParameters = new ECPrivateKeyParameters(key.getD(), params);
            holder = builder.build(signerBuilder.build(keyParameters));
        } else {
            BCRSAPrivateKey key = (BCRSAPrivateKey) privateKey;
            signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
            keyParameters = new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent());
            holder = builder.build(signerBuilder.build(keyParameters));
        }
        return holder.toASN1Structure().getEncoded();
    } catch (Exception e) {
        throw new WeGooCryptoException(CryptoExceptionMassageEnum.generate_cert_err, e);
    }
}
Also used : ECDomainParameters(com.github.zhenwei.core.crypto.params.ECDomainParameters) BCRSAPrivateKey(com.github.zhenwei.provider.jcajce.provider.asymmetric.rsa.BCRSAPrivateKey) X500Name(com.github.zhenwei.core.asn1.x500.X500Name) RSAKeyParameters(com.github.zhenwei.core.crypto.params.RSAKeyParameters) BcRSAContentSignerBuilder(com.github.zhenwei.pkix.operator.bc.BcRSAContentSignerBuilder) Random(java.util.Random) BcContentSignerBuilder(com.github.zhenwei.pkix.operator.bc.BcContentSignerBuilder) Date(java.util.Date) WeGooCryptoException(com.github.zhenwei.core.exception.WeGooCryptoException) BCECPrivateKey(com.github.zhenwei.provider.jcajce.provider.asymmetric.ec.BCECPrivateKey) ECPrivateKeyParameters(com.github.zhenwei.core.crypto.params.ECPrivateKeyParameters) WeGooCryptoException(com.github.zhenwei.core.exception.WeGooCryptoException) AsymmetricKeyParameter(com.github.zhenwei.core.crypto.params.AsymmetricKeyParameter) X509v3CertificateBuilder(com.github.zhenwei.pkix.cert.X509v3CertificateBuilder) ECParameterSpec(com.github.zhenwei.provider.jce.spec.ECParameterSpec) X509CertificateHolder(com.github.zhenwei.pkix.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) BcX509ExtensionUtils(com.github.zhenwei.pkix.cert.bc.BcX509ExtensionUtils) BcECContentSignerBuilder(com.github.zhenwei.pkix.operator.bc.BcECContentSignerBuilder)

Example 45 with KeyUsage

use of com.github.zhenwei.core.asn1.x509.KeyUsage in project java-security-private-ca by googleapis.

the class CreateCertificateTemplate method createCertificateTemplate.

/* Creates a Certificate template. These templates can be reused for common
  certificate issuance scenarios. */
public static void createCertificateTemplate(String project, String location, String certificateTemplateId) throws IOException, ExecutionException, InterruptedException, TimeoutException {
    /* Initialize client that will be used to send requests. This client only needs to be created
    once, and can be reused for multiple requests. After completing all of your requests, call
    the `certificateAuthorityServiceClient.close()` method on the client to safely
    clean up any remaining background resources. */
    try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = CertificateAuthorityServiceClient.create()) {
        /* Describes any predefined X.509 values set by this template.
      The provided extensions are copied over to certificate requests that use this template.*/
        KeyUsage keyUsage = KeyUsage.newBuilder().setBaseKeyUsage(KeyUsageOptions.newBuilder().setDigitalSignature(true).setKeyEncipherment(true).build()).setExtendedKeyUsage(ExtendedKeyUsageOptions.newBuilder().setServerAuth(true).build()).build();
        CaOptions caOptions = CaOptions.newBuilder().setIsCa(false).build();
        /* CEL expression that is evaluated against the Subject and
      Subject Alternative Name of the certificate before it is issued. */
        Expr expr = Expr.newBuilder().setExpression("subject_alt_names.all(san, san.type == DNS)").build();
        // Set the certificate issuance schema.
        CertificateTemplate certificateTemplate = CertificateTemplate.newBuilder().setPredefinedValues(X509Parameters.newBuilder().setKeyUsage(keyUsage).setCaOptions(caOptions).build()).setIdentityConstraints(CertificateIdentityConstraints.newBuilder().setCelExpression(expr).setAllowSubjectPassthrough(false).setAllowSubjectAltNamesPassthrough(false).build()).build();
        // Set the parent and certificate template properties.
        CreateCertificateTemplateRequest certificateTemplateRequest = CreateCertificateTemplateRequest.newBuilder().setParent(LocationName.of(project, location).toString()).setCertificateTemplate(certificateTemplate).setCertificateTemplateId(certificateTemplateId).build();
        // Create Template request.
        ApiFuture<Operation> futureCall = certificateAuthorityServiceClient.createCertificateTemplateCallable().futureCall(certificateTemplateRequest);
        Operation response = futureCall.get(60, TimeUnit.SECONDS);
        if (response.hasError()) {
            System.out.println("Error creating certificate template ! " + response.getError());
            return;
        }
        System.out.println("Successfully created certificate template ! " + response.getName());
    }
}
Also used : CreateCertificateTemplateRequest(com.google.cloud.security.privateca.v1.CreateCertificateTemplateRequest) Expr(com.google.type.Expr) CertificateTemplate(com.google.cloud.security.privateca.v1.CertificateTemplate) CertificateAuthorityServiceClient(com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient) KeyUsage(com.google.cloud.security.privateca.v1.KeyUsage) CaOptions(com.google.cloud.security.privateca.v1.X509Parameters.CaOptions) Operation(com.google.longrunning.Operation)

Aggregations

KeyUsage (org.bouncycastle.asn1.x509.KeyUsage)49 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)40 X500Name (org.bouncycastle.asn1.x500.X500Name)33 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)30 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)30 X509Certificate (java.security.cert.X509Certificate)29 Date (java.util.Date)29 ExtendedKeyUsage (org.bouncycastle.asn1.x509.ExtendedKeyUsage)29 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)27 ContentSigner (org.bouncycastle.operator.ContentSigner)24 BigInteger (java.math.BigInteger)23 GeneralName (org.bouncycastle.asn1.x509.GeneralName)21 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)21 IOException (java.io.IOException)20 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)19 JcaX509ExtensionUtils (org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils)16 HashSet (java.util.HashSet)15 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)15 KeyPurposeId (org.bouncycastle.asn1.x509.KeyPurposeId)15 Extension (org.bouncycastle.asn1.x509.Extension)14