Search in sources :

Example 1 with DigestCalculatorProvider

use of org.bouncycastle.operator.DigestCalculatorProvider in project robovm by robovm.

the class JcaDigestCalculatorProviderBuilder method build.

public DigestCalculatorProvider build() throws OperatorCreationException {
    return new DigestCalculatorProvider() {

        public DigestCalculator get(final AlgorithmIdentifier algorithm) throws OperatorCreationException {
            final DigestOutputStream stream;
            try {
                MessageDigest dig = helper.createDigest(algorithm);
                stream = new DigestOutputStream(dig);
            } catch (GeneralSecurityException e) {
                throw new OperatorCreationException("exception on setup: " + e, e);
            }
            return new DigestCalculator() {

                public AlgorithmIdentifier getAlgorithmIdentifier() {
                    return algorithm;
                }

                public OutputStream getOutputStream() {
                    return stream;
                }

                public byte[] getDigest() {
                    return stream.getDigest();
                }
            };
        }
    };
}
Also used : DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) GeneralSecurityException(java.security.GeneralSecurityException) DigestCalculator(org.bouncycastle.operator.DigestCalculator) MessageDigest(java.security.MessageDigest) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 2 with DigestCalculatorProvider

use of org.bouncycastle.operator.DigestCalculatorProvider in project wso2-synapse by wso2.

the class OCSPVerifierTest method testOCSPVerifier.

/**
 * A fake certificate signed by a fake CA is made as the revoked certificate. The created OCSP response to the
 * OCSP request will say that that the fake peer certificate is revoked. the SingleResp derived from the OCSP
 * response will be put the the cache against the serial number of the fake peer certificate. Since the SingleResp
 * which corresponds to the revokedSerialNumber is in the cache, there will NOT be a call to a remote OCSP server.
 * Note that the serviceUrl passed to cache.setCacheValue(..) is null since it is not needed.
 *
 * @throws Exception
 */
public void testOCSPVerifier() throws Exception {
    // Add BouncyCastle as Security Provider.
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    Utils utils = new Utils();
    // Create fake CA certificate.
    KeyPair caKeyPair = utils.generateRSAKeyPair();
    X509Certificate caCert = utils.generateFakeRootCert(caKeyPair);
    // Create fake peer certificate signed by the fake CA private key. This will be a revoked certificate.
    KeyPair peerKeyPair = utils.generateRSAKeyPair();
    BigInteger revokedSerialNumber = BigInteger.valueOf(111);
    X509Certificate revokedCertificate = generateFakePeerCert(revokedSerialNumber, peerKeyPair.getPublic(), caKeyPair.getPrivate(), caCert);
    // Create OCSP request to check if certificate with "serialNumber == revokedSerialNumber" is revoked.
    OCSPReq request = getOCSPRequest(caCert, revokedSerialNumber);
    // Create OCSP response saying that certificate with given serialNumber is revoked.
    // CertificateID revokedID = new CertificateID(CertificateID.HASH_SHA1, caCert, revokedSerialNumber);
    byte[] issuerCertEnc = caCert.getEncoded();
    X509CertificateHolder certificateHolder = new X509CertificateHolder(issuerCertEnc);
    DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build();
    // CertID structure is used to uniquely identify certificates that are the subject of
    // an OCSP request or response and has an ASN.1 definition. CertID structure is defined in RFC 2560
    CertificateID revokedID = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), certificateHolder, revokedSerialNumber);
    OCSPResp response = generateOCSPResponse(request, certificateHolder, caKeyPair.getPrivate(), caKeyPair.getPublic(), revokedID);
    SingleResp singleResp = ((BasicOCSPResp) response.getResponseObject()).getResponses()[0];
    OCSPCache cache = OCSPCache.getCache();
    cache.init(5, 5);
    cache.setCacheValue(revokedSerialNumber, singleResp, request, null);
    OCSPVerifier ocspVerifier = new OCSPVerifier(cache);
    RevocationStatus status = ocspVerifier.checkRevocationStatus(revokedCertificate, caCert);
    // the cache will have the SingleResponse derived from the OCSP response and it will be checked to see if the
    // fake certificate is revoked. So the status should be REVOKED.
    assertTrue(status == RevocationStatus.REVOKED);
}
Also used : OCSPCache(org.apache.synapse.transport.certificatevalidation.ocsp.OCSPCache) X509Certificate(java.security.cert.X509Certificate) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OCSPVerifier(org.apache.synapse.transport.certificatevalidation.ocsp.OCSPVerifier)

Example 3 with DigestCalculatorProvider

use of org.bouncycastle.operator.DigestCalculatorProvider in project keystore-explorer by kaikramer.

the class JarSigner method createSignatureBlock.

private static byte[] createSignatureBlock(byte[] toSign, PrivateKey privateKey, X509Certificate[] certificateChain, SignatureType signatureType, String tsaUrl, Provider provider) throws CryptoException {
    try {
        List<X509Certificate> certList = new ArrayList<>();
        Collections.addAll(certList, certificateChain);
        DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
        JcaContentSignerBuilder csb = new JcaContentSignerBuilder(signatureType.jce()).setSecureRandom(SecureRandom.getInstance("SHA1PRNG"));
        if (provider != null) {
            csb.setProvider(provider);
        }
        JcaSignerInfoGeneratorBuilder siGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digCalcProv);
        // remove cmsAlgorithmProtect for compatibility reasons
        SignerInfoGenerator sigGen = siGeneratorBuilder.build(csb.build(privateKey), certificateChain[0]);
        final CMSAttributeTableGenerator sAttrGen = sigGen.getSignedAttributeTableGenerator();
        sigGen = new SignerInfoGenerator(sigGen, new DefaultSignedAttributeTableGenerator() {

            @Override
            public AttributeTable getAttributes(@SuppressWarnings("rawtypes") Map parameters) {
                AttributeTable ret = sAttrGen.getAttributes(parameters);
                return ret.remove(CMSAttributes.cmsAlgorithmProtect);
            }
        }, sigGen.getUnsignedAttributeTableGenerator());
        CMSSignedDataGenerator dataGen = new CMSSignedDataGenerator();
        dataGen.addSignerInfoGenerator(sigGen);
        dataGen.addCertificates(new JcaCertStore(certList));
        CMSSignedData signedData = dataGen.generate(new CMSProcessableByteArray(toSign), true);
        // now let TSA time-stamp the signature
        if (tsaUrl != null && !tsaUrl.isEmpty()) {
            signedData = addTimestamp(tsaUrl, signedData);
        }
        return signedData.getEncoded();
    } catch (Exception ex) {
        throw new CryptoException(res.getString("SignatureBlockCreationFailed.exception.message"), ex);
    }
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) DefaultSignedAttributeTableGenerator(org.bouncycastle.cms.DefaultSignedAttributeTableGenerator) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) CryptoException(org.kse.crypto.CryptoException) IOException(java.io.IOException) JcaSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) CMSAttributeTableGenerator(org.bouncycastle.cms.CMSAttributeTableGenerator) SignerInfoGenerator(org.bouncycastle.cms.SignerInfoGenerator) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) CryptoException(org.kse.crypto.CryptoException) Map(java.util.Map)

Example 4 with DigestCalculatorProvider

use of org.bouncycastle.operator.DigestCalculatorProvider in project tika by apache.

the class Pkcs7Parser method parse.

public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException {
    try {
        DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
        CMSSignedDataParser parser = new CMSSignedDataParser(digestCalculatorProvider, new CloseShieldInputStream(stream));
        try {
            CMSTypedStream content = parser.getSignedContent();
            if (content == null) {
                throw new TikaException("cannot parse detached pkcs7 signature (no signed data to parse)");
            }
            try (InputStream input = content.getContentStream()) {
                Parser delegate = context.get(Parser.class, EmptyParser.INSTANCE);
                delegate.parse(input, handler, metadata, context);
            }
        } finally {
            parser.close();
        }
    } catch (OperatorCreationException e) {
        throw new TikaException("Unable to create DigestCalculatorProvider", e);
    } catch (CMSException e) {
        throw new TikaException("Unable to parse pkcs7 signed data", e);
    }
}
Also used : CMSSignedDataParser(org.bouncycastle.cms.CMSSignedDataParser) TikaException(org.apache.tika.exception.TikaException) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) CloseShieldInputStream(org.apache.commons.io.input.CloseShieldInputStream) InputStream(java.io.InputStream) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CloseShieldInputStream(org.apache.commons.io.input.CloseShieldInputStream) CMSTypedStream(org.bouncycastle.cms.CMSTypedStream) Parser(org.apache.tika.parser.Parser) AbstractParser(org.apache.tika.parser.AbstractParser) CMSSignedDataParser(org.bouncycastle.cms.CMSSignedDataParser) EmptyParser(org.apache.tika.parser.EmptyParser) CMSException(org.bouncycastle.cms.CMSException)

Example 5 with DigestCalculatorProvider

use of org.bouncycastle.operator.DigestCalculatorProvider 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)

Aggregations

DigestCalculatorProvider (org.bouncycastle.operator.DigestCalculatorProvider)11 JcaDigestCalculatorProviderBuilder (org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder)10 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)7 X509Certificate (java.security.cert.X509Certificate)5 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)5 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)5 ArrayList (java.util.ArrayList)4 JcaCertStore (org.bouncycastle.cert.jcajce.JcaCertStore)4 CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)4 CMSSignedData (org.bouncycastle.cms.CMSSignedData)4 CMSSignedDataGenerator (org.bouncycastle.cms.CMSSignedDataGenerator)4 JcaSignerInfoGeneratorBuilder (org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder)4 ContentSigner (org.bouncycastle.operator.ContentSigner)4 IOException (java.io.IOException)3 BigInteger (java.math.BigInteger)3 SignerInfoGenerator (org.bouncycastle.cms.SignerInfoGenerator)3 DigestCalculator (org.bouncycastle.operator.DigestCalculator)3 FileInputStream (java.io.FileInputStream)2 InputStream (java.io.InputStream)2 MessageDigest (java.security.MessageDigest)2