Search in sources :

Example 21 with ExtendedKeyUsage

use of com.github.zhenwei.core.asn1.x509.ExtendedKeyUsage in project zookeeper by apache.

the class X509TestHelpers method newCert.

/**
 * Using the private key of the given CA key pair and the Subject of the given CA cert as the Issuer, issues a
 * new cert with the given subject and public key. The returned certificate, combined with the private key half
 * of the <code>certPublicKey</code>, should be used as the key store.
 * @param caCert the certificate of the CA that's doing the signing.
 * @param caKeyPair the key pair of the CA. The private key will be used to sign. The public key must match the
 *                  public key in the <code>caCert</code>.
 * @param certSubject the subject field of the new cert being issued.
 * @param certPublicKey the public key of the new cert being issued.
 * @param expirationMillis the expiration of the cert being issued, in milliseconds from now.
 * @return a new certificate signed by the CA's private key.
 * @throws IOException
 * @throws OperatorCreationException
 * @throws GeneralSecurityException
 */
public static X509Certificate newCert(X509Certificate caCert, KeyPair caKeyPair, X500Name certSubject, PublicKey certPublicKey, long expirationMillis) throws IOException, OperatorCreationException, GeneralSecurityException {
    if (!caKeyPair.getPublic().equals(caCert.getPublicKey())) {
        throw new IllegalArgumentException("CA private key does not match the public key in the CA cert");
    }
    Date now = new Date();
    X509v3CertificateBuilder builder = initCertBuilder(new X500Name(caCert.getIssuerDN().getName()), now, new Date(now.getTime() + expirationMillis), certSubject, certPublicKey);
    // not a CA
    builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
    builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    builder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth }));
    builder.addExtension(Extension.subjectAlternativeName, false, getLocalhostSubjectAltNames());
    return buildAndSignCertificate(caKeyPair.getPrivate(), builder);
}
Also used : KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) Date(java.util.Date)

Example 22 with ExtendedKeyUsage

use of com.github.zhenwei.core.asn1.x509.ExtendedKeyUsage in project jruby-openssl by jruby.

the class X509Extension method value.

@JRubyMethod
public RubyString value(final ThreadContext context) {
    if (this.value instanceof RubyString) {
        // return the same as set
        return (RubyString) this.value;
    }
    final Ruby runtime = context.runtime;
    final String oid = getRealObjectID().getId();
    try {
        if (oid.equals("2.5.29.19")) {
            // basicConstraints
            ASN1Sequence seq2 = (ASN1Sequence) ASN1.readObject(getRealValueEncoded());
            final ByteList val = new ByteList(32);
            if (seq2.size() > 0) {
                val.append(CA_);
                ASN1Encodable obj0 = seq2.getObjectAt(0);
                final boolean bool = ((ASN1Boolean) obj0).isTrue();
                val.append(bool ? TRUE : FALSE);
            }
            if (seq2.size() > 1) {
                val.append(", pathlen:".getBytes());
                val.append(seq2.getObjectAt(1).toString().getBytes());
            }
            return runtime.newString(val);
        }
        if (oid.equals("2.5.29.15")) {
            // keyUsage
            final byte[] enc = getRealValueEncoded();
            byte b3 = 0;
            byte b2 = enc[2];
            if (enc.length > 3)
                b3 = enc[3];
            final ByteList val = new ByteList(64);
            byte[] sep = NULL;
            if ((b2 & (byte) 128) != 0) {
                val.append(sep);
                val.append(Decipher_Only);
                sep = SEP;
            }
            if ((b3 & (byte) 128) != 0) {
                val.append(sep);
                val.append(Digital_Signature);
                sep = SEP;
            }
            if ((b3 & (byte) 64) != 0) {
                val.append(sep);
                val.append(Non_Repudiation);
                sep = SEP;
            }
            if ((b3 & (byte) 32) != 0) {
                val.append(sep);
                val.append(Key_Encipherment);
                sep = SEP;
            }
            if ((b3 & (byte) 16) != 0) {
                val.append(sep);
                val.append(Data_Encipherment);
                sep = SEP;
            }
            if ((b3 & (byte) 8) != 0) {
                val.append(sep);
                val.append(Key_Agreement);
                sep = SEP;
            }
            if ((b3 & (byte) 4) != 0) {
                val.append(sep);
                val.append(Certificate_Sign);
                sep = SEP;
            }
            if ((b3 & (byte) 2) != 0) {
                val.append(sep);
                val.append(CRL_Sign);
                sep = SEP;
            }
            if ((b3 & (byte) 1) != 0) {
                // sep = SEP;
                val.append(sep);
                // sep = SEP;
                val.append(Encipher_Only);
            }
            return runtime.newString(val);
        }
        if (oid.equals("2.16.840.1.113730.1.1")) {
            // nsCertType
            final byte b0 = getRealValueEncoded()[0];
            final ByteList val = new ByteList(64);
            byte[] sep = NULL;
            if ((b0 & (byte) 128) != 0) {
                val.append(sep);
                val.append(SSL_Client);
                sep = SEP;
            }
            if ((b0 & (byte) 64) != 0) {
                val.append(sep);
                val.append(SSL_Server);
                sep = SEP;
            }
            if ((b0 & (byte) 32) != 0) {
                val.append(sep);
                val.append(SMIME);
                sep = SEP;
            }
            if ((b0 & (byte) 16) != 0) {
                val.append(sep);
                val.append(Object_Signing);
                sep = SEP;
            }
            if ((b0 & (byte) 8) != 0) {
                val.append(sep);
                val.append(Unused);
                sep = SEP;
            }
            if ((b0 & (byte) 4) != 0) {
                val.append(sep);
                val.append(SSL_CA);
                sep = SEP;
            }
            if ((b0 & (byte) 2) != 0) {
                val.append(sep);
                val.append(SMIME_CA);
                sep = SEP;
            }
            if ((b0 & (byte) 1) != 0) {
                val.append(sep);
                val.append(Object_Signing_CA);
            }
            return runtime.newString(val);
        }
        if (oid.equals("2.5.29.14")) {
            // subjectKeyIdentifier
            ASN1Encodable value = getRealValue();
            if (value instanceof ASN1OctetString) {
                byte[] octets = ((ASN1OctetString) value).getOctets();
                if (octets.length > 0 && octets[0] == BERTags.OCTET_STRING) {
                    // read nested octets
                    value = ASN1.readObject(octets);
                }
            }
            return runtime.newString(hexBytes(keyidBytes(value.toASN1Primitive()), 0));
        }
        if (oid.equals("2.5.29.35")) {
            // authorityKeyIdentifier
            ASN1Encodable value = getRealValue();
            if (value instanceof ASN1OctetString) {
                value = ASN1.readObject(((ASN1OctetString) value).getOctets());
            }
            final ByteList val = new ByteList(72);
            if (value instanceof ASN1Sequence) {
                final ASN1Sequence seq = (ASN1Sequence) value;
                final int size = seq.size();
                if (size == 0)
                    return RubyString.newEmptyString(runtime);
                for (int i = 0; i < size; i++) {
                    final ASN1Encodable enc = seq.getObjectAt(i);
                    if (enc instanceof ASN1TaggedObject) {
                        ASN1Primitive obj = ((ASN1TaggedObject) enc).getObject();
                        switch(((ASN1TaggedObject) enc).getTagNo()) {
                            case 0:
                                ASN1Primitive keyid = obj;
                                val.append(keyid_);
                                hexBytes(keyidBytes(keyid), val);
                                break;
                            case 1:
                                GeneralName name;
                                if (obj instanceof ASN1Sequence) {
                                    // GeneralNames -> toASN1Primitive()
                                    GeneralName[] names = GeneralNames.getInstance(obj).getNames();
                                    name = names.length > 0 ? names[0] : null;
                                } else {
                                    name = GeneralName.getInstance(obj);
                                }
                                if (name != null)
                                    formatGeneralName(name, val, true);
                                break;
                            case // serial
                            2:
                                val.append(new byte[] { 's', 'e', 'r', 'i', 'a', 'l', ':' });
                                if (obj instanceof ASN1Integer) {
                                    hexBytes(((ASN1Integer) obj).getValue().toByteArray(), val);
                                } else {
                                    hexBytes(((ASN1OctetString) obj).getOctets(), val);
                                }
                                break;
                        }
                    } else if (size == 1) {
                        ASN1Primitive keyid = enc.toASN1Primitive();
                        hexBytes(keyidBytes(keyid), val);
                    }
                    val.append('\n');
                }
                return runtime.newString(val);
            }
            hexBytes(keyidBytes(value.toASN1Primitive()), val).append('\n');
            return runtime.newString(val);
        }
        if (oid.equals("2.5.29.21")) {
            // CRLReason
            final IRubyObject value = getValue(runtime);
            switch(RubyNumeric.fix2int(value)) {
                case 0:
                    return runtime.newString(new ByteList(Unspecified));
                case 1:
                    return RubyString.newString(runtime, "Key Compromise");
                case 2:
                    return RubyString.newString(runtime, "CA Compromise");
                case 3:
                    return RubyString.newString(runtime, "Affiliation Changed");
                case 4:
                    return RubyString.newString(runtime, "Superseded");
                case 5:
                    return RubyString.newString(runtime, "Cessation Of Operation");
                case 6:
                    return RubyString.newString(runtime, "Certificate Hold");
                case 8:
                    return RubyString.newString(runtime, "Remove From CRL");
                case 9:
                    return RubyString.newString(runtime, "Privilege Withdrawn");
                default:
                    return runtime.newString(new ByteList(Unspecified));
            }
        }
        if (oid.equals("2.5.29.17") || oid.equals("2.5.29.18")) {
            // subjectAltName || issuerAltName
            try {
                ASN1Encodable value = getRealValue();
                final ByteList val = new ByteList(64);
                if (value instanceof ASN1TaggedObject) {
                    formatGeneralName(GeneralName.getInstance(value), val, false);
                    return runtime.newString(val);
                }
                if (value instanceof GeneralName) {
                    formatGeneralName((GeneralName) value, val, false);
                    return runtime.newString(val);
                }
                if (value instanceof ASN1OctetString) {
                    // decoded octets will end up as an ASN1Sequence instance :
                    value = ASN1.readObject(((ASN1OctetString) value).getOctets());
                }
                if (value instanceof ASN1TaggedObject) {
                    // DERTaggedObject (issuerAltName wrapping)
                    formatGeneralName(GeneralName.getInstance(value), val, false);
                    return runtime.newString(val);
                }
                final GeneralName[] names = GeneralNames.getInstance(value).getNames();
                for (int i = 0; i < names.length; i++) {
                    boolean other = formatGeneralName(names[i], val, false);
                    if (i < names.length - 1) {
                        if (other)
                            val.append(';');
                        else
                            val.append(',').append(' ');
                    }
                }
                return runtime.newString(val);
            } catch (IllegalArgumentException e) {
                debugStackTrace(runtime, e);
                return rawValueAsString(context);
            }
        }
        if (oid.equals("2.5.29.37")) {
            // extendedKeyUsage
            final ByteList val = new ByteList(64);
            if (this.value instanceof ASN1Sequence) {
                // opt "short" path
                final ASN1Sequence seq = (ASN1Sequence) this.value;
                final int size = seq.size();
                for (int i = 0; i < size; i++) {
                    ASN1Encodable o = seq.getObjectAt(i);
                    String name = o.toString();
                    Integer nid = ASN1.oid2nid(runtime, new ASN1ObjectIdentifier(name));
                    if (nid != null)
                        name = ASN1.nid2ln(runtime, nid);
                    if (name == null)
                        name = o.toString();
                    val.append(ByteList.plain(name));
                    if (i < size - 1)
                        val.append(',').append(' ');
                }
                return runtime.newString(val);
            }
            final IRubyObject value = getValue(runtime);
            if (value instanceof RubyArray) {
                final RubyArray arr = (RubyArray) value;
                final int size = arr.size();
                for (int i = 0; i < size; i++) {
                    IRubyObject entry = arr.eltInternal(i);
                    if ("ObjectId".equals(entry.getMetaClass().getBaseName())) {
                        entry = entry.callMethod(context, "ln");
                    } else if (entry.respondsTo("value")) {
                        entry = entry.callMethod(context, "value");
                    }
                    val.append(entry.asString().getByteList());
                    if (i < size - 1)
                        val.append(',').append(' ');
                }
            }
            return runtime.newString(val);
        }
        return rawValueAsString(context);
    } catch (IOException e) {
        debugStackTrace(runtime, e);
        throw newExtensionError(runtime, e);
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ByteList(org.jruby.util.ByteList) RubyArray(org.jruby.RubyArray) RubyString(org.jruby.RubyString) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) DEROctetString(org.bouncycastle.asn1.DEROctetString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) RubyString(org.jruby.RubyString) ASN1String(org.bouncycastle.asn1.ASN1String) DERUniversalString(org.bouncycastle.asn1.DERUniversalString) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) IOException(java.io.IOException) IRubyObject(org.jruby.runtime.builtin.IRubyObject) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ASN1Boolean(org.bouncycastle.asn1.ASN1Boolean) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Ruby(org.jruby.Ruby) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) JRubyMethod(org.jruby.anno.JRubyMethod)

Example 23 with ExtendedKeyUsage

use of com.github.zhenwei.core.asn1.x509.ExtendedKeyUsage in project xipki by xipki.

the class A2gChecker method checkExtnExtendedKeyUsage.

// method checkExtnCrlDistributionPoints
void checkExtnExtendedKeyUsage(StringBuilder failureMsg, byte[] extnValue, Extensions requestedExtns, ExtensionControl extnControl) {
    Set<String> isUsages = new HashSet<>();
    org.bouncycastle.asn1.x509.ExtendedKeyUsage keyusage = org.bouncycastle.asn1.x509.ExtendedKeyUsage.getInstance(extnValue);
    KeyPurposeId[] usages = keyusage.getUsages();
    if (usages != null) {
        for (KeyPurposeId usage : usages) {
            isUsages.add(usage.getId());
        }
    }
    Set<String> expectedUsages = new HashSet<>();
    Set<ExtKeyUsageControl> requiredExtKeyusage = caller.getExtKeyusage(true);
    if (requiredExtKeyusage != null) {
        for (ExtKeyUsageControl usage : requiredExtKeyusage) {
            expectedUsages.add(usage.getExtKeyUsage().getId());
        }
    }
    Set<ExtKeyUsageControl> optionalExtKeyusage = caller.getExtKeyusage(false);
    if (requestedExtns != null && extnControl.isRequest() && isNotEmpty(optionalExtKeyusage)) {
        Extension extension = requestedExtns.getExtension(Extension.extendedKeyUsage);
        if (extension != null) {
            org.bouncycastle.asn1.x509.ExtendedKeyUsage reqKeyUsage = org.bouncycastle.asn1.x509.ExtendedKeyUsage.getInstance(extension.getParsedValue());
            for (ExtKeyUsageControl k : optionalExtKeyusage) {
                if (reqKeyUsage.hasKeyPurposeId(KeyPurposeId.getInstance(k.getExtKeyUsage()))) {
                    expectedUsages.add(k.getExtKeyUsage().getId());
                }
            }
        }
    }
    if (isEmpty(expectedUsages)) {
        byte[] constantExtValue = caller.getConstantExtensionValue(Extension.extendedKeyUsage);
        if (constantExtValue != null) {
            expectedUsages = getExtKeyUsage(constantExtValue);
        }
    }
    Set<String> diffs = strInBnotInA(expectedUsages, isUsages);
    if (isNotEmpty(diffs)) {
        failureMsg.append("usages ").append(diffs).append(" are present but not expected; ");
    }
    diffs = strInBnotInA(isUsages, expectedUsages);
    if (isNotEmpty(diffs)) {
        failureMsg.append("usages ").append(diffs).append(" are absent but are required; ");
    }
}
Also used : AdmissionExtension(org.xipki.ca.certprofile.xijson.AdmissionExtension) org.bouncycastle.asn1.x509(org.bouncycastle.asn1.x509) ExtKeyUsageControl(org.xipki.ca.api.profile.Certprofile.ExtKeyUsageControl)

Example 24 with ExtendedKeyUsage

use of com.github.zhenwei.core.asn1.x509.ExtendedKeyUsage in project athenz by AthenZ.

the class Crypto method generateX509Certificate.

public static X509Certificate generateX509Certificate(PKCS10CertificationRequest certReq, PrivateKey caPrivateKey, X500Name issuer, int validityTimeout, boolean basicConstraints) {
    // set validity for the given number of minutes from now
    Date notBefore = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(notBefore);
    cal.add(Calendar.MINUTE, validityTimeout);
    Date notAfter = cal.getTime();
    // Generate self-signed certificate
    X509Certificate cert;
    try {
        JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest(certReq);
        PublicKey publicKey = jcaPKCS10CertificationRequest.getPublicKey();
        X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(issuer, BigInteger.valueOf(System.currentTimeMillis()), notBefore, notAfter, certReq.getSubject(), publicKey).addExtension(Extension.basicConstraints, false, new BasicConstraints(basicConstraints)).addExtension(Extension.keyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment)).addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
        // see if we have the dns/rfc822/ip address extensions specified in the csr
        ArrayList<GeneralName> altNames = new ArrayList<>();
        Attribute[] certAttributes = jcaPKCS10CertificationRequest.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (certAttributes != null && certAttributes.length > 0) {
            for (Attribute attribute : certAttributes) {
                Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                if (gns == null) {
                    continue;
                }
                GeneralName[] names = gns.getNames();
                for (GeneralName name : names) {
                    switch(name.getTagNo()) {
                        case GeneralName.dNSName:
                        case GeneralName.iPAddress:
                        case GeneralName.rfc822Name:
                        case GeneralName.uniformResourceIdentifier:
                            altNames.add(name);
                            break;
                    }
                }
            }
            if (!altNames.isEmpty()) {
                caBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(altNames.toArray(new GeneralName[0])));
            }
        }
        String signatureAlgorithm = getSignatureAlgorithm(caPrivateKey.getAlgorithm(), SHA256);
        ContentSigner caSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC_PROVIDER).build(caPrivateKey);
        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC_PROVIDER);
        cert = converter.getCertificate(caBuilder.build(caSigner));
    } catch (CertificateException ex) {
        LOG.error("generateX509Certificate: Caught CertificateException when generating certificate: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (OperatorCreationException ex) {
        LOG.error("generateX509Certificate: Caught OperatorCreationException when creating JcaContentSignerBuilder: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (InvalidKeyException ex) {
        LOG.error("generateX509Certificate: Caught InvalidKeySpecException, invalid key spec is being used: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOG.error("generateX509Certificate: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (Exception ex) {
        LOG.error("generateX509Certificate: unable to generate X509 Certificate: {}", ex.getMessage());
        throw new CryptoException("Unable to generate X509 Certificate");
    }
    return cert;
}
Also used : Attribute(org.bouncycastle.asn1.pkcs.Attribute) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) Extensions(org.bouncycastle.asn1.x509.Extensions) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) X509KeyUsage(org.bouncycastle.jce.X509KeyUsage) JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) BCECPublicKey(org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey) ContentSigner(org.bouncycastle.operator.ContentSigner) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CMSException(org.bouncycastle.cms.CMSException) PKCSException(org.bouncycastle.pkcs.PKCSException) PEMException(org.bouncycastle.openssl.PEMException) UnknownHostException(java.net.UnknownHostException) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 25 with ExtendedKeyUsage

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

the class ProvOcspRevocationChecker method validatedOcspResponse.

static boolean validatedOcspResponse(BasicOCSPResponse basicResp, PKIXCertRevocationCheckerParameters parameters, byte[] nonce, X509Certificate responderCert, JcaJceHelper helper) throws CertPathValidatorException {
    try {
        ASN1Sequence certs = basicResp.getCerts();
        Signature sig = helper.createSignature(getSignatureName(basicResp.getSignatureAlgorithm()));
        X509Certificate sigCert = getSignerCert(basicResp, parameters.getSigningCert(), responderCert, helper);
        if (sigCert == null && certs == null) {
            throw new CertPathValidatorException("OCSP responder certificate not found");
        }
        if (sigCert != null) {
            sig.initVerify(sigCert.getPublicKey());
        } else {
            CertificateFactory cf = helper.createCertificateFactory("X.509");
            X509Certificate ocspCert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certs.getObjectAt(0).toASN1Primitive().getEncoded()));
            // check cert signed by CA
            ocspCert.verify(parameters.getSigningCert().getPublicKey());
            // check cert valid
            ocspCert.checkValidity(parameters.getValidDate());
            // check ID
            if (!responderMatches(basicResp.getTbsResponseData().getResponderID(), ocspCert, helper)) {
                throw new CertPathValidatorException("responder certificate does not match responderID", null, parameters.getCertPath(), parameters.getIndex());
            }
            // TODO: RFC 6960 allows for a "no check" extension - where present it means the CA says the cert
            // will remain valid for it's lifetime. If any caching is added here that should be taken into account.
            // check we are valid
            List extendedKeyUsage = ocspCert.getExtendedKeyUsage();
            if (extendedKeyUsage == null || !extendedKeyUsage.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) {
                throw new CertPathValidatorException("responder certificate not valid for signing OCSP responses", null, parameters.getCertPath(), parameters.getIndex());
            }
            sig.initVerify(ocspCert);
        }
        sig.update(basicResp.getTbsResponseData().getEncoded(ASN1Encoding.DER));
        if (sig.verify(basicResp.getSignature().getBytes())) {
            if (nonce != null) {
                Extensions exts = basicResp.getTbsResponseData().getResponseExtensions();
                com.github.zhenwei.core.asn1.x509.Extension ext = exts.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
                if (!Arrays.areEqual(nonce, ext.getExtnValue().getOctets())) {
                    throw new CertPathValidatorException("nonce mismatch in OCSP response", null, parameters.getCertPath(), parameters.getIndex());
                }
            }
            return true;
        }
        return false;
    } catch (CertPathValidatorException e) {
        throw e;
    } catch (GeneralSecurityException e) {
        throw new CertPathValidatorException("OCSP response failure: " + e.getMessage(), e, parameters.getCertPath(), parameters.getIndex());
    } catch (IOException e) {
        throw new CertPathValidatorException("OCSP response failure: " + e.getMessage(), e, parameters.getCertPath(), parameters.getIndex());
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) Extensions(com.github.zhenwei.core.asn1.x509.Extensions) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) ByteArrayInputStream(java.io.ByteArrayInputStream) Signature(java.security.Signature) List(java.util.List)

Aggregations

ExtendedKeyUsage (org.bouncycastle.asn1.x509.ExtendedKeyUsage)35 KeyPurposeId (org.bouncycastle.asn1.x509.KeyPurposeId)24 KeyUsage (org.bouncycastle.asn1.x509.KeyUsage)21 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)19 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)19 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)18 X500Name (org.bouncycastle.asn1.x500.X500Name)17 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)17 ContentSigner (org.bouncycastle.operator.ContentSigner)17 Date (java.util.Date)16 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)14 X509Certificate (java.security.cert.X509Certificate)13 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)12 DEROctetString (org.bouncycastle.asn1.DEROctetString)11 Extension (org.bouncycastle.asn1.x509.Extension)11 GeneralName (org.bouncycastle.asn1.x509.GeneralName)11 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)10 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)9 JcaX509ExtensionUtils (org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8