Search in sources :

Example 86 with Signature

use of com.github.zhenwei.core.asn1.ocsp.Signature in project LinLong-Java by zhenwei1108.

the class CertPathValidatorUtilities method findTrustAnchor.

/**
 * Search the given Set of TrustAnchor's for one that is the issuer of the given X509 certificate.
 * Uses the specified provider for signature verification, or the default provider if null.
 *
 * @param cert         the X509 certificate
 * @param trustAnchors a Set of TrustAnchor's
 * @param sigProvider  the provider to use for signature verification
 * @return the <code>TrustAnchor</code> object if found or
 * <code>null</code> if not.
 * @throws AnnotatedException if a TrustAnchor was found but the signature verification on the
 *                            given certificate has thrown an exception.
 */
protected static TrustAnchor findTrustAnchor(X509Certificate cert, Set trustAnchors, String sigProvider) throws AnnotatedException {
    TrustAnchor trust = null;
    PublicKey trustPublicKey = null;
    Exception invalidKeyEx = null;
    X509CertSelector certSelectX509 = new X509CertSelector();
    final X500Principal certIssuerPrincipal = cert.getIssuerX500Principal();
    certSelectX509.setSubject(certIssuerPrincipal);
    X500Name certIssuerName = null;
    Iterator iter = trustAnchors.iterator();
    while (iter.hasNext() && trust == null) {
        trust = (TrustAnchor) iter.next();
        if (trust.getTrustedCert() != null) {
            if (certSelectX509.match(trust.getTrustedCert())) {
                trustPublicKey = trust.getTrustedCert().getPublicKey();
            } else {
                trust = null;
            }
        } else if (trust.getCA() != null && trust.getCAName() != null && trust.getCAPublicKey() != null) {
            if (certIssuerName == null) {
                certIssuerName = X500Name.getInstance(certIssuerPrincipal.getEncoded());
            }
            try {
                X500Name caName = X500Name.getInstance(trust.getCA().getEncoded());
                if (certIssuerName.equals(caName)) {
                    trustPublicKey = trust.getCAPublicKey();
                } else {
                    trust = null;
                }
            } catch (IllegalArgumentException ex) {
                trust = null;
            }
        } else {
            trust = null;
        }
        if (trustPublicKey != null) {
            try {
                verifyX509Certificate(cert, trustPublicKey, sigProvider);
            } catch (Exception ex) {
                invalidKeyEx = ex;
                trust = null;
                trustPublicKey = null;
            }
        }
    }
    if (trust == null && invalidKeyEx != null) {
        throw new AnnotatedException("TrustAnchor found but certificate validation failed.", invalidKeyEx);
    }
    return trust;
}
Also used : PublicKey(java.security.PublicKey) DSAPublicKey(java.security.interfaces.DSAPublicKey) Iterator(java.util.Iterator) X500Principal(javax.security.auth.x500.X500Principal) TrustAnchor(java.security.cert.TrustAnchor) X509CertSelector(java.security.cert.X509CertSelector) X500Name(com.github.zhenwei.core.asn1.x500.X500Name) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ParseException(java.text.ParseException) CertStoreException(java.security.cert.CertStoreException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) CRLException(java.security.cert.CRLException) StoreException(com.github.zhenwei.core.util.StoreException) CertificateParsingException(java.security.cert.CertificateParsingException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException) ExtCertPathBuilderException(com.github.zhenwei.provider.jce.exception.ExtCertPathBuilderException)

Example 87 with Signature

use of com.github.zhenwei.core.asn1.ocsp.Signature in project LinLong-Java by zhenwei1108.

the class OcspCache method getOcspResponse.

static OCSPResponse getOcspResponse(CertID certID, PKIXCertRevocationCheckerParameters parameters, URI ocspResponder, X509Certificate responderCert, List<Extension> ocspExtensions, JcaJceHelper helper) throws CertPathValidatorException {
    Map<CertID, OCSPResponse> responseMap = null;
    WeakReference<Map<CertID, OCSPResponse>> markerRef = cache.get(ocspResponder);
    if (markerRef != null) {
        responseMap = markerRef.get();
    }
    if (responseMap != null) {
        OCSPResponse response = responseMap.get(certID);
        if (response != null) {
            BasicOCSPResponse basicResp = BasicOCSPResponse.getInstance(ASN1OctetString.getInstance(response.getResponseBytes().getResponse()).getOctets());
            ResponseData responseData = ResponseData.getInstance(basicResp.getTbsResponseData());
            ASN1Sequence s = responseData.getResponses();
            for (int i = 0; i != s.size(); i++) {
                SingleResponse resp = SingleResponse.getInstance(s.getObjectAt(i));
                if (certID.equals(resp.getCertID())) {
                    ASN1GeneralizedTime nextUp = resp.getNextUpdate();
                    try {
                        if (nextUp != null && parameters.getValidDate().after(nextUp.getDate())) {
                            responseMap.remove(certID);
                            response = null;
                        }
                    } catch (ParseException e) {
                        // this should never happen, but...
                        responseMap.remove(certID);
                        response = null;
                    }
                }
            }
            if (response != null) {
                return response;
            }
        }
    }
    URL ocspUrl;
    try {
        ocspUrl = ocspResponder.toURL();
    } catch (MalformedURLException e) {
        throw new CertPathValidatorException("configuration error: " + e.getMessage(), e, parameters.getCertPath(), parameters.getIndex());
    }
    // 
    // basic request generation
    // 
    ASN1EncodableVector requests = new ASN1EncodableVector();
    requests.add(new Request(certID, null));
    List exts = ocspExtensions;
    ASN1EncodableVector requestExtensions = new ASN1EncodableVector();
    byte[] nonce = null;
    for (int i = 0; i != exts.size(); i++) {
        Extension ext = (Extension) exts.get(i);
        byte[] value = ext.getValue();
        if (OCSPObjectIdentifiers.id_pkix_ocsp_nonce.getId().equals(ext.getId())) {
            nonce = value;
        }
        requestExtensions.add(new com.github.zhenwei.core.asn1.x509.Extension(new ASN1ObjectIdentifier(ext.getId()), ext.isCritical(), value));
    }
    // TODO: configure originator
    TBSRequest tbsReq = new TBSRequest(null, new DERSequence(requests), Extensions.getInstance(new DERSequence(requestExtensions)));
    com.github.zhenwei.core.asn1.ocsp.Signature signature = null;
    try {
        byte[] request = new OCSPRequest(tbsReq, signature).getEncoded();
        HttpURLConnection ocspCon = (HttpURLConnection) ocspUrl.openConnection();
        ocspCon.setConnectTimeout(DEFAULT_TIMEOUT);
        ocspCon.setReadTimeout(DEFAULT_TIMEOUT);
        ocspCon.setDoOutput(true);
        ocspCon.setDoInput(true);
        ocspCon.setRequestMethod("POST");
        ocspCon.setRequestProperty("Content-type", "application/ocsp-request");
        ocspCon.setRequestProperty("Content-length", String.valueOf(request.length));
        OutputStream reqOut = ocspCon.getOutputStream();
        reqOut.write(request);
        reqOut.flush();
        InputStream reqIn = ocspCon.getInputStream();
        int contentLength = ocspCon.getContentLength();
        if (contentLength < 0) {
            // TODO: make configurable
            contentLength = DEFAULT_MAX_RESPONSE_SIZE;
        }
        OCSPResponse response = OCSPResponse.getInstance(Streams.readAllLimited(reqIn, contentLength));
        if (OCSPResponseStatus.SUCCESSFUL == response.getResponseStatus().getIntValue()) {
            boolean validated = false;
            ResponseBytes respBytes = ResponseBytes.getInstance(response.getResponseBytes());
            if (respBytes.getResponseType().equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic)) {
                BasicOCSPResponse basicResp = BasicOCSPResponse.getInstance(respBytes.getResponse().getOctets());
                validated = ProvOcspRevocationChecker.validatedOcspResponse(basicResp, parameters, nonce, responderCert, helper);
            }
            if (!validated) {
                throw new CertPathValidatorException("OCSP response failed to validate", null, parameters.getCertPath(), parameters.getIndex());
            }
            markerRef = cache.get(ocspResponder);
            if (markerRef != null) {
                responseMap = markerRef.get();
                responseMap.put(certID, response);
            } else {
                responseMap = new HashMap<CertID, OCSPResponse>();
                responseMap.put(certID, response);
                cache.put(ocspResponder, new WeakReference<Map<CertID, OCSPResponse>>(responseMap));
            }
            return response;
        } else {
            throw new CertPathValidatorException("OCSP responder failed: " + response.getResponseStatus().getValue(), null, parameters.getCertPath(), parameters.getIndex());
        }
    } catch (IOException e) {
        throw new CertPathValidatorException("configuration error: " + e.getMessage(), e, parameters.getCertPath(), parameters.getIndex());
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) SingleResponse(com.github.zhenwei.core.asn1.ocsp.SingleResponse) CertID(com.github.zhenwei.core.asn1.ocsp.CertID) OutputStream(java.io.OutputStream) ASN1GeneralizedTime(com.github.zhenwei.core.asn1.ASN1GeneralizedTime) URL(java.net.URL) DERSequence(com.github.zhenwei.core.asn1.DERSequence) HttpURLConnection(java.net.HttpURLConnection) BasicOCSPResponse(com.github.zhenwei.core.asn1.ocsp.BasicOCSPResponse) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) List(java.util.List) OCSPResponse(com.github.zhenwei.core.asn1.ocsp.OCSPResponse) BasicOCSPResponse(com.github.zhenwei.core.asn1.ocsp.BasicOCSPResponse) InputStream(java.io.InputStream) ResponseData(com.github.zhenwei.core.asn1.ocsp.ResponseData) TBSRequest(com.github.zhenwei.core.asn1.ocsp.TBSRequest) OCSPRequest(com.github.zhenwei.core.asn1.ocsp.OCSPRequest) Request(com.github.zhenwei.core.asn1.ocsp.Request) IOException(java.io.IOException) TBSRequest(com.github.zhenwei.core.asn1.ocsp.TBSRequest) Extension(java.security.cert.Extension) ResponseBytes(com.github.zhenwei.core.asn1.ocsp.ResponseBytes) CertPathValidatorException(java.security.cert.CertPathValidatorException) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) ParseException(java.text.ParseException) HashMap(java.util.HashMap) Map(java.util.Map) WeakHashMap(java.util.WeakHashMap) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) OCSPRequest(com.github.zhenwei.core.asn1.ocsp.OCSPRequest)

Example 88 with Signature

use of com.github.zhenwei.core.asn1.ocsp.Signature in project LinLong-Java by zhenwei1108.

the class PKIXCertPathValidatorSpi method engineValidate.

public CertPathValidatorResult engineValidate(CertPath certPath, CertPathParameters params) throws CertPathValidatorException, InvalidAlgorithmParameterException {
    PKIXExtendedParameters paramsPKIX;
    if (params instanceof PKIXParameters) {
        PKIXExtendedParameters.Builder paramsPKIXBldr = new PKIXExtendedParameters.Builder((PKIXParameters) params);
        if (params instanceof ExtendedPKIXParameters) {
            ExtendedPKIXParameters extPKIX = (ExtendedPKIXParameters) params;
            paramsPKIXBldr.setUseDeltasEnabled(extPKIX.isUseDeltasEnabled());
            paramsPKIXBldr.setValidityModel(extPKIX.getValidityModel());
        }
        paramsPKIX = paramsPKIXBldr.build();
    } else if (params instanceof PKIXExtendedBuilderParameters) {
        paramsPKIX = ((PKIXExtendedBuilderParameters) params).getBaseParameters();
    } else if (params instanceof PKIXExtendedParameters) {
        paramsPKIX = (PKIXExtendedParameters) params;
    } else {
        throw new InvalidAlgorithmParameterException("Parameters must be a " + PKIXParameters.class.getName() + " instance.");
    }
    if (paramsPKIX.getTrustAnchors() == null) {
        throw new InvalidAlgorithmParameterException("trustAnchors is null, this is not allowed for certification path validation.");
    }
    // 
    // 6.1.1 - inputs
    // 
    // 
    // (a)
    // 
    List certs = certPath.getCertificates();
    int n = certs.size();
    if (certs.isEmpty()) {
        throw new CertPathValidatorException("Certification path is empty.", null, certPath, -1);
    }
    // 
    // (b)
    // 
    final Date currentDate = new Date();
    final Date validityDate = CertPathValidatorUtilities.getValidityDate(paramsPKIX, currentDate);
    // 
    // (c)
    // 
    Set userInitialPolicySet = paramsPKIX.getInitialPolicies();
    // 
    // (d)
    // 
    TrustAnchor trust;
    try {
        trust = CertPathValidatorUtilities.findTrustAnchor((X509Certificate) certs.get(certs.size() - 1), paramsPKIX.getTrustAnchors(), paramsPKIX.getSigProvider());
        if (trust == null) {
            throw new CertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1);
        }
        checkCertificate(trust.getTrustedCert());
    } catch (AnnotatedException e) {
        throw new CertPathValidatorException(e.getMessage(), e.getUnderlyingException(), certPath, certs.size() - 1);
    }
    // RFC 5280 - CRLs must originate from the same trust anchor as the target certificate.
    paramsPKIX = new PKIXExtendedParameters.Builder(paramsPKIX).setTrustAnchor(trust).build();
    // 
    // (e), (f), (g) are part of the paramsPKIX object.
    // 
    Iterator certIter;
    int index = 0;
    int i;
    // Certificate for each interation of the validation loop
    // Signature information for each iteration of the validation loop
    // 
    // 6.1.2 - setup
    // 
    // 
    // (a)
    // 
    List[] policyNodes = new ArrayList[n + 1];
    for (int j = 0; j < policyNodes.length; j++) {
        policyNodes[j] = new ArrayList();
    }
    Set policySet = new HashSet();
    policySet.add(RFC3280CertPathUtilities.ANY_POLICY);
    PKIXPolicyNode validPolicyTree = new PKIXPolicyNode(new ArrayList(), 0, policySet, null, new HashSet(), RFC3280CertPathUtilities.ANY_POLICY, false);
    policyNodes[0].add(validPolicyTree);
    // 
    // (b) and (c)
    // 
    PKIXNameConstraintValidator nameConstraintValidator = new PKIXNameConstraintValidator();
    // (d)
    // 
    int explicitPolicy;
    Set acceptablePolicies = new HashSet();
    if (paramsPKIX.isExplicitPolicyRequired()) {
        explicitPolicy = 0;
    } else {
        explicitPolicy = n + 1;
    }
    // 
    // (e)
    // 
    int inhibitAnyPolicy;
    if (paramsPKIX.isAnyPolicyInhibited()) {
        inhibitAnyPolicy = 0;
    } else {
        inhibitAnyPolicy = n + 1;
    }
    // 
    // (f)
    // 
    int policyMapping;
    if (paramsPKIX.isPolicyMappingInhibited()) {
        policyMapping = 0;
    } else {
        policyMapping = n + 1;
    }
    // 
    // (g), (h), (i), (j)
    // 
    PublicKey workingPublicKey;
    X500Name workingIssuerName;
    X509Certificate sign = trust.getTrustedCert();
    try {
        if (sign != null) {
            workingIssuerName = PrincipalUtils.getSubjectPrincipal(sign);
            workingPublicKey = sign.getPublicKey();
        } else {
            workingIssuerName = PrincipalUtils.getCA(trust);
            workingPublicKey = trust.getCAPublicKey();
        }
    } catch (RuntimeException ex) {
        throw new ExtCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", ex, certPath, -1);
    }
    AlgorithmIdentifier workingAlgId = null;
    try {
        workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey);
    } catch (CertPathValidatorException e) {
        throw new ExtCertPathValidatorException("Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1);
    }
    ASN1ObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.getAlgorithm();
    ASN1Encodable workingPublicKeyParameters = workingAlgId.getParameters();
    // 
    // (k)
    // 
    int maxPathLength = n;
    if (paramsPKIX.getTargetConstraints() != null && !paramsPKIX.getTargetConstraints().match((X509Certificate) certs.get(0))) {
        throw new ExtCertPathValidatorException("Target certificate in certification path does not match targetConstraints.", null, certPath, 0);
    }
    // 
    // initialize CertPathChecker's
    // 
    List pathCheckers = paramsPKIX.getCertPathCheckers();
    certIter = pathCheckers.iterator();
    while (certIter.hasNext()) {
        ((PKIXCertPathChecker) certIter.next()).init(false);
    }
    // 
    // initialize RevocationChecker
    // 
    ProvCrlRevocationChecker revocationChecker;
    if (paramsPKIX.isRevocationEnabled()) {
        revocationChecker = new ProvCrlRevocationChecker(helper);
    } else {
        revocationChecker = null;
    }
    X509Certificate cert = null;
    for (index = certs.size() - 1; index >= 0; index--) {
        // try
        // {
        // 
        // i as defined in the algorithm description
        // 
        i = n - index;
        // 
        // set certificate to be checked in this round
        // sign and workingPublicKey and workingIssuerName are set
        // at the end of the for loop and initialized the
        // first time from the TrustAnchor
        // 
        cert = (X509Certificate) certs.get(index);
        boolean verificationAlreadyPerformed = (index == certs.size() - 1);
        try {
            checkCertificate(cert);
        } catch (AnnotatedException e) {
            throw new CertPathValidatorException(e.getMessage(), e.getUnderlyingException(), certPath, index);
        }
        // 
        // 6.1.3
        // 
        RFC3280CertPathUtilities.processCertA(certPath, paramsPKIX, validityDate, revocationChecker, index, workingPublicKey, verificationAlreadyPerformed, workingIssuerName, sign);
        RFC3280CertPathUtilities.processCertBC(certPath, index, nameConstraintValidator, isForCRLCheck);
        validPolicyTree = RFC3280CertPathUtilities.processCertD(certPath, index, acceptablePolicies, validPolicyTree, policyNodes, inhibitAnyPolicy, isForCRLCheck);
        validPolicyTree = RFC3280CertPathUtilities.processCertE(certPath, index, validPolicyTree);
        RFC3280CertPathUtilities.processCertF(certPath, index, validPolicyTree, explicitPolicy);
        // 
        if (i != n) {
            if (cert != null && cert.getVersion() == 1) {
                // we've found the trust anchor at the top of the path, ignore and keep going
                if ((i == 1) && cert.equals(trust.getTrustedCert())) {
                    continue;
                }
                throw new CertPathValidatorException("Version 1 certificates can't be used as CA ones.", null, certPath, index);
            }
            RFC3280CertPathUtilities.prepareNextCertA(certPath, index);
            validPolicyTree = RFC3280CertPathUtilities.prepareCertB(certPath, index, policyNodes, validPolicyTree, policyMapping);
            RFC3280CertPathUtilities.prepareNextCertG(certPath, index, nameConstraintValidator);
            // (h)
            explicitPolicy = RFC3280CertPathUtilities.prepareNextCertH1(certPath, index, explicitPolicy);
            policyMapping = RFC3280CertPathUtilities.prepareNextCertH2(certPath, index, policyMapping);
            inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertH3(certPath, index, inhibitAnyPolicy);
            // 
            // (i)
            // 
            explicitPolicy = RFC3280CertPathUtilities.prepareNextCertI1(certPath, index, explicitPolicy);
            policyMapping = RFC3280CertPathUtilities.prepareNextCertI2(certPath, index, policyMapping);
            // (j)
            inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertJ(certPath, index, inhibitAnyPolicy);
            // (k)
            RFC3280CertPathUtilities.prepareNextCertK(certPath, index);
            // (l)
            maxPathLength = RFC3280CertPathUtilities.prepareNextCertL(certPath, index, maxPathLength);
            // (m)
            maxPathLength = RFC3280CertPathUtilities.prepareNextCertM(certPath, index, maxPathLength);
            // (n)
            RFC3280CertPathUtilities.prepareNextCertN(certPath, index);
            Set criticalExtensions = cert.getCriticalExtensionOIDs();
            if (criticalExtensions != null) {
                criticalExtensions = new HashSet(criticalExtensions);
                // these extensions are handled by the algorithm
                criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE);
                criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
                criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS);
                criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY);
                criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
                criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
                criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS);
                criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS);
                criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME);
                criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS);
            } else {
                criticalExtensions = new HashSet();
            }
            // (o)
            RFC3280CertPathUtilities.prepareNextCertO(certPath, index, criticalExtensions, pathCheckers);
            // set signing certificate for next round
            sign = cert;
            // (c)
            workingIssuerName = PrincipalUtils.getSubjectPrincipal(sign);
            // (d)
            try {
                workingPublicKey = CertPathValidatorUtilities.getNextWorkingKey(certPath.getCertificates(), index, helper);
            } catch (CertPathValidatorException e) {
                throw new CertPathValidatorException("Next working key could not be retrieved.", e, certPath, index);
            }
            workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey);
            // (f)
            workingPublicKeyAlgorithm = workingAlgId.getAlgorithm();
            // (e)
            workingPublicKeyParameters = workingAlgId.getParameters();
        }
    }
    // 
    // 6.1.5 Wrap-up procedure
    // 
    explicitPolicy = RFC3280CertPathUtilities.wrapupCertA(explicitPolicy, cert);
    explicitPolicy = RFC3280CertPathUtilities.wrapupCertB(certPath, index + 1, explicitPolicy);
    // 
    // (c) (d) and (e) are already done
    // 
    // 
    // (f)
    // 
    Set criticalExtensions = cert.getCriticalExtensionOIDs();
    if (criticalExtensions != null) {
        criticalExtensions = new HashSet(criticalExtensions);
        // these extensions are handled by the algorithm
        criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE);
        criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
        criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS);
        criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY);
        criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
        criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
        criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS);
        criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS);
        criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME);
        criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS);
        criticalExtensions.remove(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS);
        criticalExtensions.remove(Extension.extendedKeyUsage.getId());
    } else {
        criticalExtensions = new HashSet();
    }
    RFC3280CertPathUtilities.wrapupCertF(certPath, index + 1, pathCheckers, criticalExtensions);
    PKIXPolicyNode intersection = RFC3280CertPathUtilities.wrapupCertG(certPath, paramsPKIX, userInitialPolicySet, index + 1, policyNodes, validPolicyTree, acceptablePolicies);
    if ((explicitPolicy > 0) || (intersection != null)) {
        return new PKIXCertPathValidatorResult(trust, intersection, cert.getPublicKey());
    }
    throw new CertPathValidatorException("Path processing failed on policy.", null, certPath, index);
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) ArrayList(java.util.ArrayList) X500Name(com.github.zhenwei.core.asn1.x500.X500Name) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) ExtendedPKIXParameters(com.github.zhenwei.provider.x509.ExtendedPKIXParameters) PKIXParameters(java.security.cert.PKIXParameters) PKIXExtendedBuilderParameters(com.github.zhenwei.provider.jcajce.PKIXExtendedBuilderParameters) PKIXCertPathChecker(java.security.cert.PKIXCertPathChecker) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) ASN1Encodable(com.github.zhenwei.core.asn1.ASN1Encodable) HashSet(java.util.HashSet) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PublicKey(java.security.PublicKey) TrustAnchor(java.security.cert.TrustAnchor) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) BCX509Certificate(com.github.zhenwei.provider.jcajce.interfaces.BCX509Certificate) 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) ExtendedPKIXParameters(com.github.zhenwei.provider.x509.ExtendedPKIXParameters) PKIXCertPathValidatorResult(java.security.cert.PKIXCertPathValidatorResult) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)

Example 89 with Signature

use of com.github.zhenwei.core.asn1.ocsp.Signature in project LinLong-Java by zhenwei1108.

the class X509CertificateObject method checkSignature.

private void checkSignature(PublicKey key, Signature signature) throws CertificateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
    if (!isAlgIdEqual(c.getSignatureAlgorithm(), c.getTBSCertificate().getSignature())) {
        throw new CertificateException("signature algorithm in TBS cert not same as outer cert");
    }
    ASN1Encodable params = c.getSignatureAlgorithm().getParameters();
    // TODO This should go after the initVerify?
    X509SignatureUtil.setSignatureParameters(signature, params);
    signature.initVerify(key);
    signature.update(this.getTBSCertificate());
    if (!signature.verify(this.getSignature())) {
        throw new SignatureException("certificate does not verify with supplied key");
    }
}
Also used : CertificateException(java.security.cert.CertificateException) ASN1Encodable(com.github.zhenwei.core.asn1.ASN1Encodable) SignatureException(java.security.SignatureException)

Example 90 with Signature

use of com.github.zhenwei.core.asn1.ocsp.Signature in project LinLong-Java by zhenwei1108.

the class NetscapeCertRequest method sign.

public void sign(PrivateKey priv_key, SecureRandom rand) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, NoSuchProviderException, InvalidKeySpecException {
    Signature sig = Signature.getInstance(sigAlg.getAlgorithm().getId(), "WeGoo");
    if (rand != null) {
        sig.initSign(priv_key, rand);
    } else {
        sig.initSign(priv_key);
    }
    ASN1EncodableVector pkac = new ASN1EncodableVector();
    pkac.add(getKeySpec());
    pkac.add(new DERIA5String(challenge));
    try {
        sig.update(new DERSequence(pkac).getEncoded(ASN1Encoding.DER));
    } catch (IOException ioe) {
        throw new SignatureException(ioe.getMessage());
    }
    sigBits = sig.sign();
}
Also used : DERIA5String(com.github.zhenwei.core.asn1.DERIA5String) DERSequence(com.github.zhenwei.core.asn1.DERSequence) Signature(java.security.Signature) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) IOException(java.io.IOException) SignatureException(java.security.SignatureException)

Aggregations

IOException (java.io.IOException)44 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)34 DERSequence (com.github.zhenwei.core.asn1.DERSequence)29 DERBitString (com.github.zhenwei.core.asn1.DERBitString)21 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)20 OutputStream (java.io.OutputStream)20 SignatureException (java.security.SignatureException)20 GeneralSecurityException (java.security.GeneralSecurityException)15 Signature (java.security.Signature)15 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)14 DEROctetString (com.github.zhenwei.core.asn1.DEROctetString)14 InvalidKeyException (java.security.InvalidKeyException)13 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)13 Iterator (java.util.Iterator)13 OperatorCreationException (com.github.zhenwei.pkix.operator.OperatorCreationException)11 CertificateEncodingException (java.security.cert.CertificateEncodingException)11 NoSuchProviderException (java.security.NoSuchProviderException)10 ASN1OctetString (com.github.zhenwei.core.asn1.ASN1OctetString)9 ASN1Sequence (com.github.zhenwei.core.asn1.ASN1Sequence)9 List (java.util.List)9