Example usage for org.bouncycastle.cert.ocsp BasicOCSPResp getSignatureAlgOID

List of usage examples for org.bouncycastle.cert.ocsp BasicOCSPResp getSignatureAlgOID

Introduction

In this page you can find the example usage for org.bouncycastle.cert.ocsp BasicOCSPResp getSignatureAlgOID.

Prototype

public ASN1ObjectIdentifier getSignatureAlgOID() 

Source Link

Usage

From source file:be.fedict.trust.ocsp.OcspTrustLinker.java

License:Open Source License

@Override
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData, AlgorithmPolicy algorithmPolicy)
        throws TrustLinkerResultException, Exception {
    URI ocspUri = getOcspUri(childCertificate);
    if (null == ocspUri) {
        return TrustLinkerResult.UNDECIDED;
    }//w ww. ja  v a 2  s.com
    LOG.debug("OCSP URI: " + ocspUri);

    OCSPResp ocspResp = this.ocspRepository.findOcspResponse(ocspUri, childCertificate, certificate,
            validationDate);
    if (null == ocspResp) {
        LOG.debug("OCSP response not found");
        return TrustLinkerResult.UNDECIDED;
    }

    int ocspRespStatus = ocspResp.getStatus();
    if (OCSPResponseStatus.SUCCESSFUL != ocspRespStatus) {
        LOG.debug("OCSP response status: " + ocspRespStatus);
        return TrustLinkerResult.UNDECIDED;
    }

    Object responseObject = ocspResp.getResponseObject();
    BasicOCSPResp basicOCSPResp = (BasicOCSPResp) responseObject;

    X509CertificateHolder[] responseCertificates = basicOCSPResp.getCerts();
    for (X509CertificateHolder responseCertificate : responseCertificates) {
        LOG.debug("OCSP response cert: " + responseCertificate.getSubject());
        LOG.debug("OCSP response cert issuer: " + responseCertificate.getIssuer());
    }

    algorithmPolicy.checkSignatureAlgorithm(basicOCSPResp.getSignatureAlgOID().getId(), validationDate);

    if (0 == responseCertificates.length) {
        /*
         * This means that the OCSP response has been signed by the issuing
         * CA itself.
         */
        ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(certificate.getPublicKey());
        boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider);
        if (false == verificationResult) {
            LOG.debug("OCSP response signature invalid");
            return TrustLinkerResult.UNDECIDED;
        }
    } else {
        /*
         * We're dealing with a dedicated authorized OCSP Responder
         * certificate, or of course with a CA that issues the OCSP
         * Responses itself.
         */

        X509CertificateHolder ocspResponderCertificate = responseCertificates[0];
        ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(ocspResponderCertificate);

        boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider);
        if (false == verificationResult) {
            LOG.debug("OCSP Responser response signature invalid");
            return TrustLinkerResult.UNDECIDED;
        }
        if (false == Arrays.equals(certificate.getEncoded(), ocspResponderCertificate.getEncoded())) {
            // check certificate signature algorithm
            algorithmPolicy.checkSignatureAlgorithm(
                    ocspResponderCertificate.getSignatureAlgorithm().getAlgorithm().getId(), validationDate);

            X509Certificate issuingCaCertificate;
            if (responseCertificates.length < 2) {
                // so the OCSP certificate chain only contains a single
                // entry
                LOG.debug("OCSP responder complete certificate chain missing");
                /*
                 * Here we assume that the OCSP Responder is directly signed
                 * by the CA.
                 */
                issuingCaCertificate = certificate;
            } else {
                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
                issuingCaCertificate = (X509Certificate) certificateFactory
                        .generateCertificate(new ByteArrayInputStream(responseCertificates[1].getEncoded()));
                /*
                 * Is next check really required?
                 */
                if (false == certificate.equals(issuingCaCertificate)) {
                    LOG.debug("OCSP responder certificate not issued by CA");
                    return TrustLinkerResult.UNDECIDED;
                }
            }
            // check certificate signature
            algorithmPolicy.checkSignatureAlgorithm(issuingCaCertificate.getSigAlgOID(), validationDate);

            PublicKeyTrustLinker publicKeyTrustLinker = new PublicKeyTrustLinker();
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            X509Certificate x509OcspResponderCertificate = (X509Certificate) certificateFactory
                    .generateCertificate(new ByteArrayInputStream(ocspResponderCertificate.getEncoded()));
            LOG.debug("OCSP Responder public key fingerprint: "
                    + DigestUtils.sha1Hex(x509OcspResponderCertificate.getPublicKey().getEncoded()));
            publicKeyTrustLinker.hasTrustLink(x509OcspResponderCertificate, issuingCaCertificate,
                    validationDate, revocationData, algorithmPolicy);
            if (null == x509OcspResponderCertificate
                    .getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())) {
                LOG.debug("OCSP Responder certificate should have id-pkix-ocsp-nocheck");
                /*
                 * TODO: perform CRL validation on the OCSP Responder
                 * certificate. On the other hand, do we really want to
                 * check the checker?
                 */
                return TrustLinkerResult.UNDECIDED;
            }
            List<String> extendedKeyUsage = x509OcspResponderCertificate.getExtendedKeyUsage();
            if (null == extendedKeyUsage) {
                LOG.debug("OCSP Responder certificate has no extended key usage extension");
                return TrustLinkerResult.UNDECIDED;
            }
            if (false == extendedKeyUsage.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) {
                LOG.debug("OCSP Responder certificate should have a OCSPSigning extended key usage");
                return TrustLinkerResult.UNDECIDED;
            }
        } else {
            LOG.debug("OCSP Responder certificate equals the CA certificate");
            // and the CA certificate is already trusted at this point
        }
    }

    DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build();
    CertificateID certificateId = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1),
            new JcaX509CertificateHolder(certificate), childCertificate.getSerialNumber());

    SingleResp[] singleResps = basicOCSPResp.getResponses();
    for (SingleResp singleResp : singleResps) {
        CertificateID responseCertificateId = singleResp.getCertID();
        if (false == certificateId.equals(responseCertificateId)) {
            continue;
        }
        DateTime thisUpdate = new DateTime(singleResp.getThisUpdate());
        DateTime nextUpdate;
        if (null != singleResp.getNextUpdate()) {
            nextUpdate = new DateTime(singleResp.getNextUpdate());
        } else {
            LOG.debug("no OCSP nextUpdate");
            nextUpdate = thisUpdate;
        }
        LOG.debug("OCSP thisUpdate: " + thisUpdate);
        LOG.debug("(OCSP) nextUpdate: " + nextUpdate);
        DateTime beginValidity = thisUpdate.minus(this.freshnessInterval);
        DateTime endValidity = nextUpdate.plus(this.freshnessInterval);
        DateTime validationDateTime = new DateTime(validationDate);
        if (validationDateTime.isBefore(beginValidity)) {
            LOG.warn("OCSP response not yet valid");
            continue;
        }
        if (validationDateTime.isAfter(endValidity)) {
            LOG.warn("OCSP response expired");
            continue;
        }
        if (null == singleResp.getCertStatus()) {
            LOG.debug("OCSP OK for: " + childCertificate.getSubjectX500Principal());
            addRevocationData(revocationData, ocspResp, ocspUri);
            return TrustLinkerResult.TRUSTED;
        } else {
            LOG.debug("OCSP certificate status: " + singleResp.getCertStatus().getClass().getName());
            if (singleResp.getCertStatus() instanceof RevokedStatus) {
                LOG.debug("OCSP status revoked");
            }
            addRevocationData(revocationData, ocspResp, ocspUri);
            throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_REVOCATION_STATUS,
                    "certificate revoked by OCSP");
        }
    }

    LOG.debug("no matching OCSP response entry");
    return TrustLinkerResult.UNDECIDED;
}

From source file:eu.europa.ec.markt.dss.validation102853.OCSPToken.java

License:Open Source License

/**
 * The default constructor for OCSPToken.
 *
 * @param basicOCSPResp      The basic OCSP response.
 * @param certificatePool The certificate pool used to validate/hold the certificate used to sign this OCSP response.
 *///from ww w.j a  va2 s.  c  om
public OCSPToken(final BasicOCSPResp basicOCSPResp, final CertificatePool certificatePool) {

    if (basicOCSPResp == null) {

        throw new DSSNullException(BasicOCSPResp.class);
    }
    if (certificatePool == null) {

        throw new DSSNullException(CertificatePool.class);
    }
    this.basicOCSPResp = basicOCSPResp;
    final ASN1ObjectIdentifier signatureAlgOID = basicOCSPResp.getSignatureAlgOID();
    final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.forOID(signatureAlgOID.getId());
    this.algorithmUsedToSignToken = signatureAlgorithm;
    this.extraInfo = new TokenValidationExtraInfo();
    try {

        for (final X509CertificateHolder x509CertificateHolder : basicOCSPResp.getCerts()) {

            final byte[] encoded = x509CertificateHolder.getEncoded();
            final X509Certificate x509Certificate = DSSUtils.loadCertificate(encoded);
            final CertificateToken certToken = certificatePool.getInstance(x509Certificate,
                    CertificateSourceType.OCSP_RESPONSE);
            if (isSignedBy(certToken)) {

                break;
            }
        }
    } catch (IOException e) {
        throw new DSSException(e);
    }
    if (LOG.isInfoEnabled()) {
        LOG.info("OCSP token, produced at '" + DSSUtils.formatInternal(basicOCSPResp.getProducedAt())
                + "' added.");
    }
}

From source file:eu.europa.esig.dss.x509.OCSPToken.java

License:Open Source License

/**
 * The default constructor for OCSPToken.
 *
 * @param basicOCSPResp   The basic OCSP response.
 * @param singleResp//from  ww  w  .  j  a v  a  2s  .  c  om
 */
public OCSPToken(final BasicOCSPResp basicOCSPResp, final SingleResp singleResp) {

    if (basicOCSPResp == null) {
        throw new NullPointerException();
    }
    if (singleResp == null) {
        throw new NullPointerException();
    }
    this.basicOCSPResp = basicOCSPResp;
    this.singleResp = singleResp;
    this.issuingTime = basicOCSPResp.getProducedAt();
    setStatus(singleResp.getCertStatus());
    final ASN1ObjectIdentifier signatureAlgOID = basicOCSPResp.getSignatureAlgOID();
    final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.forOID(signatureAlgOID.getId());
    this.signatureAlgorithm = signatureAlgorithm;
    this.extraInfo = new TokenValidationExtraInfo();

    if (logger.isTraceEnabled()) {
        logger.trace("OCSP token, produced at '" + DSSUtils.formatInternal(issuingTime) + "' created.");
    }
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java

License:Open Source License

/**
 * This test tests that the OCSP response contains is signed by the preferred signature algorithm specified in the request.
 * // w w  w . ja va2s . c  om
 * @throws Exception
*/
@Test
@Deprecated // This test verifies legacy behavior from EJBCA 6.1.0 and should be removed when we no longer need to support it
public void testSigAlgExtensionLegacy() throws Exception {
    loadUserCert(this.caid);

    // Try sending a request where the preferred signature algorithm in the extension is expected to be used to sign the response.

    // set ocsp configuration
    Map<String, String> map = new HashMap<String, String>();
    map.put("ocsp.signaturealgorithm",
            AlgorithmConstants.SIGALG_SHA256_WITH_RSA + ";" + AlgorithmConstants.SIGALG_SHA1_WITH_RSA);
    this.helper.alterConfig(map);

    ASN1EncodableVector algVec = new ASN1EncodableVector();
    algVec.add(X9ObjectIdentifiers.ecdsa_with_SHA256);
    algVec.add(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    ASN1Sequence algSeq = new DERSequence(algVec);
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    // RFC 6960: id-pkix-ocsp-pref-sig-algs   OBJECT IDENTIFIER ::= { id-pkix-ocsp 8 } 
    extgen.addExtension(new ASN1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp + ".8"), false, algSeq);
    Extensions exts = extgen.generate();
    assertNotNull(exts);

    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
            ocspTestCert.getSerialNumber()), exts);
    gen.setRequestExtensions(exts);
    OCSPReq req = gen.build();
    assertTrue(req.hasExtensions());

    BasicOCSPResp response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200);
    assertNotNull("Could not retrieve response, test could not continue.", response);
    assertEquals(PKCSObjectIdentifiers.sha1WithRSAEncryption, response.getSignatureAlgOID());

    // Try sending a request where the preferred signature algorithm is not compatible with the signing key, but 
    // the configured algorithm is. Expected a response signed using the first configured algorithm

    algVec = new ASN1EncodableVector();
    algVec.add(X9ObjectIdentifiers.ecdsa_with_SHA256);
    algSeq = new DERSequence(algVec);

    extgen = new ExtensionsGenerator();
    extgen.addExtension(new ASN1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp + ".8"), false, algSeq);
    exts = extgen.generate();
    assertNotNull(exts);

    gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
            ocspTestCert.getSerialNumber()), exts);
    gen.setRequestExtensions(exts);
    req = gen.build();
    assertTrue(req.hasExtensions());

    response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200);
    assertNotNull("Could not retrieve response, test could not continue.", response);
    assertEquals(PKCSObjectIdentifiers.sha256WithRSAEncryption, response.getSignatureAlgOID());
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java

License:Open Source License

/** This test tests that the OCSP response contains is signed by the preferred signature algorithm specified in the request. */
/* Example of the ASN.1 dump (with friendly names from the RFC added ) of what the extensions should look like.
 * /*  w w  w  . j a  va  2 s. c o m*/
 * Note that we have left out the optional
 *  PreferredSignatureAlgorithm.pubKeyAlgIdentifier
 * and
 *  AlgorithmIdentifier.parameters
 *  
 *               ...
 *  75  48:     requestExtensions [2] {
 *  77  46:       Extensions ::= SEQUENCE {
 *  79  44:         Extension ::= SEQUENCE {
 *  81   9:           extnID OBJECT IDENTIFIER '1 3 6 1 5 5 7 48 1 8'
 *  92  31:           extnValue OCTET STRING, encapsulates {
 *  94  29:             PreferredSignatureAlgorithms ::= SEQUENCE {
 *  96  12:               PreferredSignatureAlgorithm ::= SEQUENCE {
 *  98  10:                 sigIdentifier AlgorithmIdentifier ::= SEQUENCE {
 * 100   8:                   algorithm OBJECT IDENTIFIER
 *        :                     ecdsaWithSHA256 (1 2 840 10045 4 3 2)
 *        :                   }
 *        :                 }
 * 110  13:               PreferredSignatureAlgorithm ::= SEQUENCE {
 * 112  11:                 sigIdentifier AlgorithmIdentifier ::= SEQUENCE {
 * 114   9:                   algorithm OBJECT IDENTIFIER
 *        :                     sha1WithRSAEncryption (1 2 840 113549 1 1 5)
 *        :                   }
 *        :                 ...
 */
@Test
public void testSigAlgExtension() throws Exception {
    log.trace(">testSigAlgExtensionNew");
    loadUserCert(caid);
    // Try sending a request where the preferred signature algorithm in the extension is expected to be used to sign the response.
    // set ocsp configuration
    final Map<String, String> map = new HashMap<String, String>();
    map.put("ocsp.signaturealgorithm",
            AlgorithmConstants.SIGALG_SHA256_WITH_RSA + ";" + AlgorithmConstants.SIGALG_SHA1_WITH_RSA);
    helper.alterConfig(map);
    final ASN1Sequence preferredSignatureAlgorithms = getPreferredSignatureAlgorithms(
            X9ObjectIdentifiers.ecdsa_with_SHA256, PKCSObjectIdentifiers.sha1WithRSAEncryption);
    final ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
    // RFC 6960: id-pkix-ocsp-pref-sig-algs   OBJECT IDENTIFIER ::= { id-pkix-ocsp 8 } 
    extensionsGenerator.addExtension(new ASN1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp + ".8"), false,
            preferredSignatureAlgorithms);
    final Extensions extensions = extensionsGenerator.generate();
    assertNotNull(extensions);
    final OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
    ocspReqBuilder.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
            ocspTestCert.getSerialNumber()));
    ocspReqBuilder.setRequestExtensions(extensions);
    final OCSPReq ocspRequest = ocspReqBuilder.build();
    assertTrue(ocspRequest.hasExtensions());
    log.debug("base64 encoded request: " + new String(Base64.encode(ocspRequest.getEncoded(), false)));
    final BasicOCSPResp response1 = helper.sendOCSPGet(ocspRequest.getEncoded(), null,
            OCSPRespBuilder.SUCCESSFUL, 200);
    assertNotNull("Could not retrieve response, test could not continue.", response1);
    assertEquals(PKCSObjectIdentifiers.sha1WithRSAEncryption, response1.getSignatureAlgOID());
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java

License:Open Source License

/** Test with a preferred signature algorithm specified in the request that is incompatible with the singing key. */
@Test/*from  w  ww.j av a  2 s.  com*/
public void testSigAlgExtensionMismatch() throws Exception {
    log.trace(">testSigAlgExtensionNewMismatch");
    loadUserCert(caid);
    final Map<String, String> map = new HashMap<String, String>();
    map.put("ocsp.signaturealgorithm",
            AlgorithmConstants.SIGALG_SHA256_WITH_RSA + ";" + AlgorithmConstants.SIGALG_SHA1_WITH_RSA);
    helper.alterConfig(map);
    // Try sending a request where the preferred signature algorithm is not compatible with the signing key, but 
    // the configured algorithm is. Expected a response signed using the first configured algorithm
    final ASN1Sequence preferredSignatureAlgorithms = getPreferredSignatureAlgorithms(
            X9ObjectIdentifiers.ecdsa_with_SHA256);
    final ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
    extensionsGenerator.addExtension(new ASN1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp + ".8"), false,
            preferredSignatureAlgorithms);
    final Extensions extensions = extensionsGenerator.generate();
    assertNotNull(extensions);
    final OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
    ocspReqBuilder.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
            ocspTestCert.getSerialNumber()));
    ocspReqBuilder.setRequestExtensions(extensions);
    final OCSPReq ocspRequest = ocspReqBuilder.build();
    assertTrue(ocspRequest.hasExtensions());
    log.debug("base64 encoded request: " + new String(Base64.encode(ocspRequest.getEncoded(), false)));
    final BasicOCSPResp response2 = helper.sendOCSPGet(ocspRequest.getEncoded(), null,
            OCSPRespBuilder.SUCCESSFUL, 200);
    assertNotNull("Could not retrieve response, test could not continue.", response2);
    assertEquals(PKCSObjectIdentifiers.sha256WithRSAEncryption, response2.getSignatureAlgOID());
}