Search in sources :

Example 26 with CertID

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

the class PKCS12KeyStoreSpi method engineGetCertificateChain.

public Certificate[] engineGetCertificateChain(String alias) {
    if (alias == null) {
        throw new IllegalArgumentException("null alias passed to getCertificateChain.");
    }
    if (!engineIsKeyEntry(alias)) {
        return null;
    }
    Certificate c = engineGetCertificate(alias);
    if (c != null) {
        Vector cs = new Vector();
        while (c != null) {
            X509Certificate x509c = (X509Certificate) c;
            Certificate nextC = null;
            byte[] akiBytes = x509c.getExtensionValue(Extension.authorityKeyIdentifier.getId());
            if (akiBytes != null) {
                ASN1OctetString akiValue = ASN1OctetString.getInstance(akiBytes);
                AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.getInstance(akiValue.getOctets());
                byte[] keyID = aki.getKeyIdentifier();
                if (null != keyID) {
                    nextC = (Certificate) chainCerts.get(new CertId(keyID));
                }
            }
            if (nextC == null) {
                // 
                // no authority key id, try the Issuer DN
                // 
                Principal i = x509c.getIssuerDN();
                Principal s = x509c.getSubjectDN();
                if (!i.equals(s)) {
                    Enumeration e = chainCerts.keys();
                    while (e.hasMoreElements()) {
                        X509Certificate crt = (X509Certificate) chainCerts.get(e.nextElement());
                        Principal sub = crt.getSubjectDN();
                        if (sub.equals(i)) {
                            try {
                                x509c.verify(crt.getPublicKey());
                                nextC = crt;
                                break;
                            } catch (Exception ex) {
                            // continue
                            }
                        }
                    }
                }
            }
            if (cs.contains(c)) {
                // we've got a certificate chain loop time to stop
                c = null;
            } else {
                cs.addElement(c);
                if (// self signed - end of the chain
                nextC != c) {
                    c = nextC;
                } else {
                    c = null;
                }
            }
        }
        Certificate[] certChain = new Certificate[cs.size()];
        for (int i = 0; i != certChain.length; i++) {
            certChain[i] = (Certificate) cs.elementAt(i);
        }
        return certChain;
    }
    return null;
}
Also used : ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) Enumeration(java.util.Enumeration) AuthorityKeyIdentifier(com.github.zhenwei.core.asn1.x509.AuthorityKeyIdentifier) X509Certificate(java.security.cert.X509Certificate) 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) Vector(java.util.Vector) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) Principal(java.security.Principal) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 27 with CertID

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

the class ProvOcspRevocationChecker method createCertID.

private CertID createCertID(AlgorithmIdentifier digestAlg, com.github.zhenwei.core.asn1.x509.Certificate issuer, ASN1Integer serialNumber) throws CertPathValidatorException {
    try {
        MessageDigest digest = helper.createMessageDigest(MessageDigestUtils.getDigestName(digestAlg.getAlgorithm()));
        ASN1OctetString issuerNameHash = new DEROctetString(digest.digest(issuer.getSubject().getEncoded(ASN1Encoding.DER)));
        ASN1OctetString issuerKeyHash = new DEROctetString(digest.digest(issuer.getSubjectPublicKeyInfo().getPublicKeyData().getBytes()));
        return new CertID(digestAlg, issuerNameHash, issuerKeyHash, serialNumber);
    } catch (Exception e) {
        throw new CertPathValidatorException("problem creating ID: " + e, e);
    }
}
Also used : ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) CertID(com.github.zhenwei.core.asn1.ocsp.CertID) MessageDigest(java.security.MessageDigest) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString) URISyntaxException(java.net.URISyntaxException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 28 with CertID

use of com.github.zhenwei.core.asn1.ocsp.CertID 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 29 with CertID

use of com.github.zhenwei.core.asn1.ocsp.CertID in project snowflake-jdbc by snowflakedb.

the class SFTrustManager method encodeCacheToJSON.

/**
 * Encode OCSP Response Cache to JSON
 *
 * @return JSON object
 */
private static ObjectNode encodeCacheToJSON() {
    try {
        ObjectNode out = OBJECT_MAPPER.createObjectNode();
        for (Map.Entry<OcspResponseCacheKey, SFPair<Long, String>> elem : OCSP_RESPONSE_CACHE.entrySet()) {
            OcspResponseCacheKey key = elem.getKey();
            SFPair<Long, String> value0 = elem.getValue();
            long currentTimeSecond = value0.left;
            DigestCalculator digest = new SHA1DigestCalculator();
            AlgorithmIdentifier algo = digest.getAlgorithmIdentifier();
            ASN1OctetString nameHash = ASN1OctetString.getInstance(key.nameHash);
            ASN1OctetString keyHash = ASN1OctetString.getInstance(key.keyHash);
            ASN1Integer serialNumber = new ASN1Integer(key.serialNumber);
            CertID cid = new CertID(algo, nameHash, keyHash, serialNumber);
            ArrayNode vout = OBJECT_MAPPER.createArrayNode();
            vout.add(currentTimeSecond);
            vout.add(value0.right);
            out.set(Base64.encodeBase64String(cid.toASN1Primitive().getEncoded()), vout);
        }
        return out;
    } catch (IOException ex) {
        LOGGER.debug("Failed to encode ASN1 object.");
    }
    return null;
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) CertID(org.bouncycastle.asn1.ocsp.CertID) DigestCalculator(org.bouncycastle.operator.DigestCalculator) IOException(java.io.IOException) SFPair(net.snowflake.client.util.SFPair) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 30 with CertID

use of com.github.zhenwei.core.asn1.ocsp.CertID in project snowflake-jdbc by snowflakedb.

the class SFTrustManager method encodeCacheKey.

/**
 * Convert cache key to base64 encoded cert id
 *
 * @param ocsp_cache_key Cache key to encode
 */
private static String encodeCacheKey(OcspResponseCacheKey ocsp_cache_key) {
    try {
        DigestCalculator digest = new SHA1DigestCalculator();
        AlgorithmIdentifier algo = digest.getAlgorithmIdentifier();
        ASN1OctetString nameHash = ASN1OctetString.getInstance(ocsp_cache_key.nameHash);
        ASN1OctetString keyHash = ASN1OctetString.getInstance(ocsp_cache_key.keyHash);
        ASN1Integer snumber = new ASN1Integer(ocsp_cache_key.serialNumber);
        CertID cid = new CertID(algo, nameHash, keyHash, snumber);
        return Base64.encodeBase64String(cid.toASN1Primitive().getEncoded());
    } catch (Exception ex) {
        LOGGER.debug("Failed to encode cache key to base64 encoded cert id");
    }
    return null;
}
Also used : CertID(org.bouncycastle.asn1.ocsp.CertID) DigestCalculator(org.bouncycastle.operator.DigestCalculator) URISyntaxException(java.net.URISyntaxException) InvocationTargetException(java.lang.reflect.InvocationTargetException) CertificateEncodingException(java.security.cert.CertificateEncodingException) SSLInitializationException(org.apache.http.ssl.SSLInitializationException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException)

Aggregations

IOException (java.io.IOException)19 CertID (org.bouncycastle.asn1.ocsp.CertID)15 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)13 DERSequence (com.github.zhenwei.core.asn1.DERSequence)11 CertificateException (java.security.cert.CertificateException)7 X509Certificate (java.security.cert.X509Certificate)7 ASN1OctetString (com.github.zhenwei.core.asn1.ASN1OctetString)6 DEROctetString (com.github.zhenwei.core.asn1.DEROctetString)6 BigInteger (java.math.BigInteger)6 CertificateEncodingException (java.security.cert.CertificateEncodingException)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 NoSuchProviderException (java.security.NoSuchProviderException)5 ASN1BMPString (com.github.zhenwei.core.asn1.ASN1BMPString)4 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)4 DERBMPString (com.github.zhenwei.core.asn1.DERBMPString)4 Extension (org.bouncycastle.asn1.x509.Extension)4 ASN1Sequence (com.github.zhenwei.core.asn1.ASN1Sequence)3 BEROctetString (com.github.zhenwei.core.asn1.BEROctetString)3 DERTaggedObject (com.github.zhenwei.core.asn1.DERTaggedObject)3 CertID (com.github.zhenwei.core.asn1.ocsp.CertID)3