Search in sources :

Example 71 with Extensions

use of org.openecard.bouncycastle.asn1.x509.Extensions in project nifi by apache.

the class OcspCertificateValidator method getOcspStatus.

/**
 * Gets the OCSP status for the specified subject and issuer certificates.
 *
 * @param ocspStatusKey status key
 * @return ocsp status
 */
private OcspStatus getOcspStatus(final OcspRequest ocspStatusKey) {
    final X509Certificate subjectCertificate = ocspStatusKey.getSubjectCertificate();
    final X509Certificate issuerCertificate = ocspStatusKey.getIssuerCertificate();
    // initialize the default status
    final OcspStatus ocspStatus = new OcspStatus();
    ocspStatus.setVerificationStatus(VerificationStatus.Unknown);
    ocspStatus.setValidationStatus(ValidationStatus.Unknown);
    try {
        // prepare the request
        final BigInteger subjectSerialNumber = subjectCertificate.getSerialNumber();
        final DigestCalculatorProvider calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
        final CertificateID certificateId = new CertificateID(calculatorProviderBuilder.get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCertificate.getEncoded()), subjectSerialNumber);
        // generate the request
        final OCSPReqBuilder requestGenerator = new OCSPReqBuilder();
        requestGenerator.addRequest(certificateId);
        // Create a nonce to avoid replay attack
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, new DEROctetString(nonce.toByteArray()));
        requestGenerator.setRequestExtensions(new Extensions(new Extension[] { ext }));
        final OCSPReq ocspRequest = requestGenerator.build();
        // perform the request
        final Response response = getClientResponse(ocspRequest);
        // ensure the request was completed successfully
        if (Response.Status.OK.getStatusCode() != response.getStatusInfo().getStatusCode()) {
            logger.warn(String.format("OCSP request was unsuccessful (%s).", response.getStatus()));
            return ocspStatus;
        }
        // interpret the response
        OCSPResp ocspResponse = new OCSPResp(response.readEntity(InputStream.class));
        // verify the response status
        switch(ocspResponse.getStatus()) {
            case OCSPRespBuilder.SUCCESSFUL:
                ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Successful);
                break;
            case OCSPRespBuilder.INTERNAL_ERROR:
                ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.InternalError);
                break;
            case OCSPRespBuilder.MALFORMED_REQUEST:
                ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.MalformedRequest);
                break;
            case OCSPRespBuilder.SIG_REQUIRED:
                ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.SignatureRequired);
                break;
            case OCSPRespBuilder.TRY_LATER:
                ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.TryLater);
                break;
            case OCSPRespBuilder.UNAUTHORIZED:
                ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unauthorized);
                break;
            default:
                ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unknown);
                break;
        }
        // only proceed if the response was successful
        if (ocspResponse.getStatus() != OCSPRespBuilder.SUCCESSFUL) {
            logger.warn(String.format("OCSP request was unsuccessful (%s).", ocspStatus.getResponseStatus().toString()));
            return ocspStatus;
        }
        // ensure the appropriate response object
        final Object ocspResponseObject = ocspResponse.getResponseObject();
        if (ocspResponseObject == null || !(ocspResponseObject instanceof BasicOCSPResp)) {
            logger.warn(String.format("Unexpected OCSP response object: %s", ocspResponseObject));
            return ocspStatus;
        }
        // get the response object
        final BasicOCSPResp basicOcspResponse = (BasicOCSPResp) ocspResponse.getResponseObject();
        // attempt to locate the responder certificate
        final X509CertificateHolder[] responderCertificates = basicOcspResponse.getCerts();
        if (responderCertificates.length != 1) {
            logger.warn(String.format("Unexpected number of OCSP responder certificates: %s", responderCertificates.length));
            return ocspStatus;
        }
        // get the responder certificate
        final X509Certificate trustedResponderCertificate = getTrustedResponderCertificate(responderCertificates[0], issuerCertificate);
        if (trustedResponderCertificate != null) {
            // verify the response
            if (basicOcspResponse.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(trustedResponderCertificate.getPublicKey()))) {
                ocspStatus.setVerificationStatus(VerificationStatus.Verified);
            } else {
                ocspStatus.setVerificationStatus(VerificationStatus.Unverified);
            }
        } else {
            ocspStatus.setVerificationStatus(VerificationStatus.Unverified);
        }
        // validate the response
        final SingleResp[] responses = basicOcspResponse.getResponses();
        for (SingleResp singleResponse : responses) {
            final CertificateID responseCertificateId = singleResponse.getCertID();
            final BigInteger responseSerialNumber = responseCertificateId.getSerialNumber();
            if (responseSerialNumber.equals(subjectSerialNumber)) {
                Object certStatus = singleResponse.getCertStatus();
                // interpret the certificate status
                if (CertificateStatus.GOOD == certStatus) {
                    ocspStatus.setValidationStatus(ValidationStatus.Good);
                } else if (certStatus instanceof RevokedStatus) {
                    ocspStatus.setValidationStatus(ValidationStatus.Revoked);
                } else {
                    ocspStatus.setValidationStatus(ValidationStatus.Unknown);
                }
            }
        }
    } catch (final OCSPException | IOException | ProcessingException | OperatorCreationException e) {
        logger.error(e.getMessage(), e);
    } catch (CertificateException e) {
        e.printStackTrace();
    }
    return ocspStatus;
}
Also used : CertificateException(java.security.cert.CertificateException) Extensions(org.bouncycastle.asn1.x509.Extensions) DEROctetString(org.bouncycastle.asn1.DEROctetString) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) ProcessingException(javax.ws.rs.ProcessingException) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) Extension(org.bouncycastle.asn1.x509.Extension) Response(javax.ws.rs.core.Response) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder)

Example 72 with Extensions

use of org.openecard.bouncycastle.asn1.x509.Extensions in project athenz by yahoo.

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 = null;
    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 (int i = 0; i < names.length; i++) {
                    switch(names[i].getTagNo()) {
                        case GeneralName.dNSName:
                        case GeneralName.iPAddress:
                        case GeneralName.rfc822Name:
                            altNames.add(names[i]);
                            break;
                    }
                }
            }
            if (!altNames.isEmpty()) {
                caBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(altNames.toArray(new GeneralName[altNames.size()])));
            }
        }
        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) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) 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) PublicKey(java.security.PublicKey) Calendar(java.util.Calendar) ContentSigner(org.bouncycastle.operator.ContentSigner) InvalidKeyException(java.security.InvalidKeyException) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) ECPoint(org.bouncycastle.math.ec.ECPoint) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CMSException(org.bouncycastle.cms.CMSException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) SignatureException(java.security.SignatureException) FileNotFoundException(java.io.FileNotFoundException) CertificateParsingException(java.security.cert.CertificateParsingException) PEMException(org.bouncycastle.openssl.PEMException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 73 with Extensions

use of org.openecard.bouncycastle.asn1.x509.Extensions in project athenz by yahoo.

the class Crypto method extractX509CSRIPAddresses.

public static List<String> extractX509CSRIPAddresses(PKCS10CertificationRequest certReq) {
    List<String> ipAddresses = new ArrayList<>();
    Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributes) {
        for (ASN1Encodable value : attribute.getAttributeValues()) {
            Extensions extensions = Extensions.getInstance(value);
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            for (GeneralName name : gns.getNames()) {
                if (name.getTagNo() == GeneralName.iPAddress) {
                    try {
                        InetAddress addr = InetAddress.getByAddress(((DEROctetString) name.getName()).getOctets());
                        ipAddresses.add(addr.getHostAddress());
                    } catch (UnknownHostException e) {
                    }
                }
            }
        }
    }
    return ipAddresses;
}
Also used : GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) UnknownHostException(java.net.UnknownHostException) Attribute(org.bouncycastle.asn1.pkcs.Attribute) ArrayList(java.util.ArrayList) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Extensions(org.bouncycastle.asn1.x509.Extensions) InetAddress(java.net.InetAddress)

Example 74 with Extensions

use of org.openecard.bouncycastle.asn1.x509.Extensions in project BiglyBT by BiglySoftware.

the class X509CRLEntryObject method getExtensionOIDs.

private Set getExtensionOIDs(boolean critical) {
    X509Extensions extensions = c.getExtensions();
    if (extensions != null) {
        HashSet set = new HashSet();
        Enumeration e = extensions.oids();
        while (e.hasMoreElements()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
            X509Extension ext = extensions.getExtension(oid);
            if (critical == ext.isCritical()) {
                set.add(oid.getId());
            }
        }
        return set;
    }
    return null;
}
Also used : Enumeration(java.util.Enumeration) X509Extension(org.gudy.bouncycastle.asn1.x509.X509Extension) X509Extensions(org.gudy.bouncycastle.asn1.x509.X509Extensions) DERObjectIdentifier(org.gudy.bouncycastle.asn1.DERObjectIdentifier) HashSet(java.util.HashSet)

Example 75 with Extensions

use of org.openecard.bouncycastle.asn1.x509.Extensions in project BiglyBT by BiglySoftware.

the class X509CertificateObject method hasUnsupportedCriticalExtension.

@Override
public boolean hasUnsupportedCriticalExtension() {
    if (this.getVersion() == 3) {
        X509Extensions extensions = c.getTBSCertificate().getExtensions();
        if (extensions != null) {
            Enumeration e = extensions.oids();
            while (e.hasMoreElements()) {
                DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                if (oid.getId().equals("2.5.29.15") || oid.getId().equals("2.5.29.19")) {
                    continue;
                }
                X509Extension ext = extensions.getExtension(oid);
                if (ext.isCritical()) {
                    return true;
                }
            }
        }
    }
    return false;
}
Also used : X509Extension(org.gudy.bouncycastle.asn1.x509.X509Extension)

Aggregations

Extensions (org.bouncycastle.asn1.x509.Extensions)55 Extension (org.bouncycastle.asn1.x509.Extension)52 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)44 DEROctetString (org.bouncycastle.asn1.DEROctetString)37 IOException (java.io.IOException)36 HashSet (java.util.HashSet)33 Enumeration (java.util.Enumeration)30 DERIA5String (org.bouncycastle.asn1.DERIA5String)26 Date (java.util.Date)23 X500Name (org.bouncycastle.asn1.x500.X500Name)23 Set (java.util.Set)21 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)21 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)21 GeneralName (org.bouncycastle.asn1.x509.GeneralName)21 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)20 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)20 BigInteger (java.math.BigInteger)19 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)19 CertificateException (java.security.cert.CertificateException)17 X509Certificate (java.security.cert.X509Certificate)17