Search in sources :

Example 6 with BcDigestCalculatorProvider

use of org.bouncycastle.operator.bc.BcDigestCalculatorProvider in project jmeter by apache.

the class SMIMEAssertion method getResult.

public static AssertionResult getResult(SMIMEAssertionTestElement testElement, SampleResult response, String name) {
    checkForBouncycastle();
    AssertionResult res = new AssertionResult(name);
    try {
        MimeMessage msg;
        final int msgPos = testElement.getSpecificMessagePositionAsInt();
        if (msgPos < 0) {
            // means counting from end
            SampleResult[] subResults = response.getSubResults();
            final int pos = subResults.length + msgPos;
            log.debug("Getting message number: {} of {}", pos, subResults.length);
            msg = getMessageFromResponse(response, pos);
        } else {
            log.debug("Getting message number: {}", msgPos);
            msg = getMessageFromResponse(response, msgPos);
        }
        SMIMESignedParser signedParser = null;
        if (log.isDebugEnabled()) {
            log.debug("Content-type: {}", msg.getContentType());
        }
        if (msg.isMimeType("multipart/signed")) {
            // $NON-NLS-1$
            MimeMultipart multipart = (MimeMultipart) msg.getContent();
            signedParser = new SMIMESignedParser(new BcDigestCalculatorProvider(), multipart);
        } else if (// $NON-NLS-1$
        msg.isMimeType("application/pkcs7-mime") || msg.isMimeType("application/x-pkcs7-mime")) {
            // $NON-NLS-1$
            signedParser = new SMIMESignedParser(new BcDigestCalculatorProvider(), msg);
        }
        if (null != signedParser) {
            log.debug("Found signature");
            if (testElement.isNotSigned()) {
                res.setFailure(true);
                res.setFailureMessage("Mime message is signed");
            } else if (testElement.isVerifySignature() || !testElement.isSignerNoCheck()) {
                res = verifySignature(testElement, signedParser, name);
            }
        } else {
            log.debug("Did not find signature");
            if (!testElement.isNotSigned()) {
                res.setFailure(true);
                res.setFailureMessage("Mime message is not signed");
            }
        }
    } catch (MessagingException e) {
        String msg = "Cannot parse mime msg: " + e.getMessage();
        log.warn(msg, e);
        res.setFailure(true);
        res.setFailureMessage(msg);
    } catch (CMSException e) {
        res.setFailure(true);
        res.setFailureMessage("Error reading the signature: " + e.getMessage());
    } catch (SMIMEException e) {
        res.setFailure(true);
        res.setFailureMessage("Cannot extract signed body part from signature: " + e.getMessage());
    } catch (IOException e) {
        // should never happen
        log.error("Cannot read mime message content: {}", e.getMessage(), e);
        res.setError(true);
        res.setFailureMessage(e.getMessage());
    }
    return res;
}
Also used : BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) SMIMESignedParser(org.bouncycastle.mail.smime.SMIMESignedParser) SMIMEException(org.bouncycastle.mail.smime.SMIMEException) SampleResult(org.apache.jmeter.samplers.SampleResult) CMSException(org.bouncycastle.cms.CMSException)

Example 7 with BcDigestCalculatorProvider

use of org.bouncycastle.operator.bc.BcDigestCalculatorProvider in project jruby-openssl by jruby.

the class OCSPCertificateId method initializeImpl.

private IRubyObject initializeImpl(final ThreadContext context, BigInteger serial, IRubyObject issuerCert, IRubyObject digest) {
    Ruby runtime = context.getRuntime();
    Digest rubyDigest = (Digest) digest;
    ASN1ObjectIdentifier oid = ASN1.sym2Oid(runtime, rubyDigest.getName().toLowerCase());
    AlgorithmIdentifier bcAlgId = new AlgorithmIdentifier(oid);
    BcDigestCalculatorProvider calculatorProvider = new BcDigestCalculatorProvider();
    DigestCalculator calc;
    try {
        calc = calculatorProvider.get(bcAlgId);
    } catch (OperatorCreationException e) {
        throw newOCSPError(runtime, e);
    }
    X509Cert rubyCert = (X509Cert) issuerCert;
    try {
        this.bcCertId = new CertificateID(calc, new X509CertificateHolder(rubyCert.getAuxCert().getEncoded()), serial).toASN1Primitive();
    } catch (Exception e) {
        throw newOCSPError(runtime, e);
    }
    return this;
}
Also used : BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) Digest._Digest(org.jruby.ext.openssl.Digest._Digest) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) DigestCalculator(org.bouncycastle.operator.DigestCalculator) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) Ruby(org.jruby.Ruby) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) RaiseException(org.jruby.exceptions.RaiseException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 8 with BcDigestCalculatorProvider

use of org.bouncycastle.operator.bc.BcDigestCalculatorProvider in project keycloak by keycloak.

the class OCSPUtils method check.

/**
 * Requests certificate revocation status using OCSP.
 * @param cert the certificate to be checked
 * @param issuerCertificate the issuer certificate
 * @param responderURIs the OCSP responder URIs
 * @param responderCert the OCSP responder certificate
 * @param date if null, the current time is used.
 * @return a revocation status
 * @throws CertPathValidatorException
 */
private static OCSPRevocationStatus check(KeycloakSession session, X509Certificate cert, X509Certificate issuerCertificate, List<URI> responderURIs, X509Certificate responderCert, Date date) throws CertPathValidatorException {
    if (responderURIs == null || responderURIs.size() == 0)
        throw new IllegalArgumentException("Need at least one responder");
    try {
        DigestCalculator digCalc = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
        JcaCertificateID certificateID = new JcaCertificateID(digCalc, issuerCertificate, cert.getSerialNumber());
        // Create a nounce extension to protect against replay attacks
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        BigInteger nounce = BigInteger.valueOf(Math.abs(random.nextInt()));
        DEROctetString derString = new DEROctetString(nounce.toByteArray());
        Extension nounceExtension = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, derString);
        Extensions extensions = new Extensions(nounceExtension);
        OCSPReq ocspReq = new OCSPReqBuilder().addRequest(certificateID, extensions).build();
        URI responderURI = responderURIs.get(0);
        logger.log(Level.INFO, "OCSP Responder {0}", responderURI);
        try {
            OCSPResp resp = getResponse(session, ocspReq, responderURI);
            logger.log(Level.FINE, "Received a response from OCSP responder {0}, the response status is {1}", new Object[] { responderURI, resp.getStatus() });
            switch(resp.getStatus()) {
                case OCSPResp.SUCCESSFUL:
                    if (resp.getResponseObject() instanceof BasicOCSPResp) {
                        return processBasicOCSPResponse(issuerCertificate, responderCert, date, certificateID, nounce, (BasicOCSPResp) resp.getResponseObject());
                    } else {
                        throw new CertPathValidatorException("OCSP responder returned an invalid or unknown OCSP response.");
                    }
                case OCSPResp.INTERNAL_ERROR:
                case OCSPResp.TRY_LATER:
                    throw new CertPathValidatorException("Internal error/try later. OCSP response error: " + resp.getStatus(), (Throwable) null, (CertPath) null, -1, CertPathValidatorException.BasicReason.UNDETERMINED_REVOCATION_STATUS);
                case OCSPResp.SIG_REQUIRED:
                    throw new CertPathValidatorException("Invalid or missing signature. OCSP response error: " + resp.getStatus(), (Throwable) null, (CertPath) null, -1, CertPathValidatorException.BasicReason.INVALID_SIGNATURE);
                case OCSPResp.UNAUTHORIZED:
                    throw new CertPathValidatorException("Unauthorized request. OCSP response error: " + resp.getStatus(), (Throwable) null, (CertPath) null, -1, CertPathValidatorException.BasicReason.UNSPECIFIED);
                case OCSPResp.MALFORMED_REQUEST:
                default:
                    throw new CertPathValidatorException("OCSP request is malformed. OCSP response error: " + resp.getStatus(), (Throwable) null, (CertPath) null, -1, CertPathValidatorException.BasicReason.UNSPECIFIED);
            }
        } catch (IOException e) {
            logger.log(Level.FINE, "OCSP Responder \"{0}\" failed to return a valid OCSP response\n{1}", new Object[] { responderURI, e.getMessage() });
            throw new CertPathValidatorException("OCSP check failed", e);
        }
    } catch (CertificateNotYetValidException | CertificateExpiredException | OperatorCreationException | OCSPException | CertificateEncodingException | NoSuchAlgorithmException | NoSuchProviderException e) {
        logger.log(Level.FINE, e.getMessage());
        throw new CertPathValidatorException(e.getMessage(), e);
    }
}
Also used : DigestCalculator(org.bouncycastle.operator.DigestCalculator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Extensions(org.bouncycastle.asn1.x509.Extensions) URI(java.net.URI) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) JcaCertificateID(org.bouncycastle.cert.ocsp.jcajce.JcaCertificateID) SecureRandom(java.security.SecureRandom) IOException(java.io.IOException) Extension(org.bouncycastle.asn1.x509.Extension) BigInteger(java.math.BigInteger) NoSuchProviderException(java.security.NoSuchProviderException)

Aggregations

BcDigestCalculatorProvider (org.bouncycastle.operator.bc.BcDigestCalculatorProvider)8 IOException (java.io.IOException)7 BigInteger (java.math.BigInteger)4 SecureRandom (java.security.SecureRandom)4 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)4 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)4 DigestCalculator (org.bouncycastle.operator.DigestCalculator)4 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)4 X509Certificate (java.security.cert.X509Certificate)3 X500Name (org.bouncycastle.asn1.x500.X500Name)3 CertificateEncodingException (java.security.cert.CertificateEncodingException)2 Date (java.util.Date)2 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)2 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)2 KeyUsage (org.bouncycastle.asn1.x509.KeyUsage)2 CMSAbsentContent (org.bouncycastle.cms.CMSAbsentContent)2 CMSException (org.bouncycastle.cms.CMSException)2 CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)2 CMSSignedDataGenerator (org.bouncycastle.cms.CMSSignedDataGenerator)2 CMSTypedData (org.bouncycastle.cms.CMSTypedData)2