Example usage for org.bouncycastle.cert.ocsp OCSPReqBuilder setRequestorName

List of usage examples for org.bouncycastle.cert.ocsp OCSPReqBuilder setRequestorName

Introduction

In this page you can find the example usage for org.bouncycastle.cert.ocsp OCSPReqBuilder setRequestorName.

Prototype

public OCSPReqBuilder setRequestorName(GeneralName requestorName) 

Source Link

Usage

From source file:ee.ria.xroad.signer.certmanager.OcspClient.java

License:Open Source License

private static OCSPReq createRequest(X509Certificate subjectCert, X509Certificate issuerCert,
        PrivateKey signerKey, X509Certificate signerCert, String signAlgoId) throws Exception {
    OCSPReqBuilder requestBuilder = new OCSPReqBuilder();

    CertificateID id = CryptoUtils.createCertId(subjectCert, issuerCert);
    requestBuilder.addRequest(id);/*from  w  w w  .  j av  a  2 s  .c  o m*/

    if (signerKey != null && signerCert != null) {
        X509CertificateHolder signerCertHolder = new X509CertificateHolder(signerCert.getEncoded());
        ContentSigner contentSigner = CryptoUtils.createContentSigner(signAlgoId, signerKey);

        log.trace("Creating signed OCSP request for certificate '{}' (signed by {})",
                subjectCert.getSubjectX500Principal(), signerCertHolder.getSubject());

        // needs to be set when generating signed requests
        requestBuilder.setRequestorName(signerCertHolder.getSubject());

        return requestBuilder.build(contentSigner, new X509CertificateHolder[] { signerCertHolder });
    }

    log.trace("Creating unsigned OCSP request for certificate '{}'", subjectCert.getSubjectX500Principal());

    return requestBuilder.build();
}

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

License:GNU General Public License

private byte[] buildOCSPRequest(final X509Certificate signCert, final X509Certificate issuerCert,
        Extension nonceExtension) throws DSSException {
    try {//  w ww . j  a  v a 2s  . c  o  m
        final CertificateID certId = DSSRevocationUtils.getOCSPCertificateID(signCert, issuerCert);
        final OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
        ocspReqBuilder.addRequest(certId);
        ocspReqBuilder.setRequestExtensions(new Extensions(nonceExtension));

        if (configuration.hasToBeOCSPRequestSigned()) {
            JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder("SHA1withRSA");

            if (!configuration.isOCSPSigningConfigurationAvailable()) {
                throw new ConfigurationException(
                        "Configuration needed for OCSP request signing is not complete.");
            }

            SignatureToken ocspSigner = new PKCS12SignatureToken(
                    configuration.getOCSPAccessCertificateFileName(),
                    configuration.getOCSPAccessCertificatePassword());

            ContentSigner contentSigner = signerBuilder.build(ocspSigner.getPrivateKey());
            X509Certificate ocspSignerCert = ocspSigner.getCertificate();
            X509CertificateHolder[] chain = { new X509CertificateHolder(ocspSignerCert.getEncoded()) };
            GeneralName generalName = new GeneralName(
                    new JcaX509CertificateHolder(ocspSignerCert).getSubject());
            ocspReqBuilder.setRequestorName(generalName);

            return ocspReqBuilder.build(contentSigner, chain).getEncoded();
        }
        return ocspReqBuilder.build().getEncoded();
    } catch (Exception e) {
        throw new DSSException(e);
    }
}

From source file:org.cesecore.certificates.ocsp.standalone.StandaloneOcspResponseGeneratorSessionTest.java

License:Open Source License

@Test
public void testGetOcspResponseWithIncorrectDefaultResponder() throws Exception {
    // Set a fake value
    GlobalOcspConfiguration ocspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession
            .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID);
    ocspConfiguration.setOcspDefaultResponderReference("CN=FancyPants");
    globalConfigurationSession.saveConfiguration(authenticationToken, ocspConfiguration);

    cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.SIGNATUREREQUIRED, "true");

    // An OCSP request
    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), ocspSigningCertificate,
            ocspSigningCertificate.getSerialNumber()));
    Extension[] extensions = new Extension[1];
    extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
            new DEROctetString("123456789".getBytes()));
    gen.setRequestExtensions(new Extensions(extensions));
    //Create a signed request in order to test all aspects 
    KeyPair keys = KeyTools.genKeys("512", "RSA");
    // Issue a certificate to a test user
    final String endEntityName = "testGetOcspResponseWithIncorrectDefaultResponder";
    final EndEntityInformation user = new EndEntityInformation(endEntityName, "CN=" + endEntityName,
            x509ca.getCAId(), null, null, new EndEntityType(EndEntityTypes.ENDUSER), 1,
            CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, EndEntityConstants.TOKEN_USERGEN, 0, null);
    user.setStatus(EndEntityConstants.STATUS_NEW);
    user.setPassword("foo123");
    final SimpleRequestMessage certreq = new SimpleRequestMessage(keys.getPublic(), user.getUsername(),
            user.getPassword());/* w ww  .ja v a 2  s . com*/
    final X509ResponseMessage resp = (X509ResponseMessage) certificateCreateSession.createCertificate(
            authenticationToken, user, certreq, X509ResponseMessage.class, signSession.fetchCertGenParams());
    final X509Certificate ocspTestCert = (X509Certificate) resp.getCertificate();

    X509CertificateHolder chain[] = new JcaX509CertificateHolder[2];
    chain[0] = new JcaX509CertificateHolder(ocspTestCert);
    chain[1] = new JcaX509CertificateHolder(caCertificate);
    gen.setRequestorName(chain[0].getSubject());
    OCSPReq req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA")
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keys.getPrivate()), 20480), chain);
    //Now delete the original CA, making this test completely standalone.
    OcspTestUtils.deleteCa(authenticationToken, x509ca);
    activateKeyBinding(internalKeyBindingId);
    ocspResponseGeneratorSession.reloadOcspSigningCache();

    try {
        final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber();
        // Create the transaction logger for this transaction.
        TransactionLogger transactionLogger = new TransactionLogger(localTransactionId,
                GuidHolder.INSTANCE.getGlobalUid(), "");
        // Create the audit logger for this transaction.
        AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(),
                "");
        byte[] responseBytes = ocspResponseGeneratorSession
                .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger)
                .getOcspResponse();
        //We're expecting back an unsigned reply saying unauthorized, as per RFC2690 Section 2.3
        assertNotNull("OCSP responder replied null", responseBytes);
        OCSPResp response = new OCSPResp(responseBytes);
        assertEquals("Response status not OCSPRespBuilder.UNAUTHORIZED.", response.getStatus(),
                OCSPRespBuilder.UNAUTHORIZED);
        assertNull("Response should not have contained a response object.", response.getResponseObject());
    } finally {
        try {
            if (ocspTestCert != null)
                internalCertificateStoreSession.removeCertificate(ocspTestCert);
        } catch (Exception e) {
            //NOPMD: Ignore
        }
        cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.SIGNATUREREQUIRED, "false");
    }
}

From source file:org.cesecore.certificates.ocsp.standalone.StandaloneOcspResponseGeneratorSessionTest.java

License:Open Source License

/**
 * Build an OCSP request, that will optionally be signed if authentication parameters are specified
 * /*from  w ww . j  av a2  s  .  com*/
 * @param ocspAuthenticationCertificate signing certificate
 * @param ocspAuthenticationPrivateKey private key to sign with
 * @param caCertificate issuer of the queried certificate
 * @param certificateSerialnumber serial number of the certificate to be queried
 * @return
 * @throws Exception
 */
private OCSPReq buildOcspRequest(final X509Certificate ocspAuthenticationCertificate,
        final PrivateKey ocspAuthenticationPrivateKey, final X509Certificate caCertificate,
        final BigInteger certificateSerialnumber) throws Exception {
    final OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
    if (ocspAuthenticationCertificate != null) {
        // Signed requests are required to have an OCSPRequest.TBSRequest.requestorName
        ocspReqBuilder.setRequestorName(new X500Name(ocspAuthenticationCertificate.getSubjectDN().getName()));
    }
    ocspReqBuilder.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate,
            certificateSerialnumber));
    ocspReqBuilder.setRequestExtensions(
            new Extensions(new Extension[] { new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
                    new DEROctetString("123456789".getBytes())) }));
    if (ocspAuthenticationCertificate != null && ocspAuthenticationPrivateKey != null) {
        // Create a signed request
        final ContentSigner signer = new BufferingContentSigner(
                new JcaContentSignerBuilder(AlgorithmConstants.SIGALG_SHA1_WITH_RSA)
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(ocspAuthenticationPrivateKey),
                20480);
        return ocspReqBuilder.build(signer, new X509CertificateHolder[] {
                new X509CertificateHolder(ocspAuthenticationCertificate.getEncoded()) });
    } else {
        // Create an unsigned request
        return ocspReqBuilder.build();
    }
}

From source file:org.digidoc4j.impl.bdoc.ocsp.SKOnlineOCSPSource.java

License:GNU General Public License

private byte[] buildOCSPRequest(final CertificateToken signCert, final CertificateToken issuerCert,
        Extension nonceExtension) throws DSSException {
    try {//from  w w w.  ja v a 2s.c o  m
        logger.debug("Building OCSP request");
        final CertificateID certId = DSSRevocationUtils.getOCSPCertificateID(signCert, issuerCert);
        final OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
        ocspReqBuilder.addRequest(certId);
        ocspReqBuilder.setRequestExtensions(new Extensions(nonceExtension));

        if (configuration.hasToBeOCSPRequestSigned()) {
            logger.info("Using signed OCSP request");
            JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder("SHA1withRSA");

            if (!configuration.isOCSPSigningConfigurationAvailable()) {
                throw new ConfigurationException(
                        "Configuration needed for OCSP request signing is not complete.");
            }

            DSSPrivateKeyEntry keyEntry = getOCSPAccessCertificatePrivateKey();
            PrivateKey privateKey = ((KSPrivateKeyEntry) keyEntry).getPrivateKey();
            X509Certificate ocspSignerCert = keyEntry.getCertificate().getCertificate();

            ContentSigner contentSigner = signerBuilder.build(privateKey);
            X509CertificateHolder[] chain = { new X509CertificateHolder(ocspSignerCert.getEncoded()) };
            GeneralName generalName = new GeneralName(
                    new JcaX509CertificateHolder(ocspSignerCert).getSubject());
            ocspReqBuilder.setRequestorName(generalName);

            return ocspReqBuilder.build(contentSigner, chain).getEncoded();
        }
        return ocspReqBuilder.build().getEncoded();
    } catch (Exception e) {
        throw new DSSException(e);
    }
}

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

License:Open Source License

/**
 * @param serialNr serial number of the certificate to verify
 * @param cacert issuer of the certificate to verify
 * @param useGet if true GET will be used instead of POST as HTTP method
 * @return response can contain and an error code but the fnr is allways null, never returns null.
 * @throws OCSPException /*  ww  w .  jav  a2  s  .c om*/
 * @throws IOException
 * @throws OperatorCreationException if Signer couldn't be created
 * @throws KeyStoreException 
 * @throws NoSuchAlgorithmException 
 * @throws CertificateException 
 * @throws KeyManagementException 
 * @throws UnrecoverableKeyException 
 */
public OCSPUnidResponse lookup(BigInteger serialNr, X509Certificate cacert, boolean useGet)
        throws OCSPException, IOException, OperatorCreationException, UnrecoverableKeyException,
        KeyManagementException, CertificateException, NoSuchAlgorithmException, KeyStoreException {
    if (this.httpReqPath == null) {
        // If we didn't pass a url to the constructor and the cert does not have the URL, we will fail...
        OCSPUnidResponse ret = new OCSPUnidResponse();
        ret.setErrorCode(OCSPUnidResponse.ERROR_NO_OCSP_URI);
        return ret;
    }
    final OCSPReqBuilder gen = new OCSPReqBuilder();
    final CertificateID certId = new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(),
            (X509Certificate) cacert, serialNr);
    gen.addRequest(certId);
    if (!useGet) {
        // Add a nonce to the request
        gen.setRequestExtensions(this.extensions);
    }
    final OCSPReq req;
    if (this.signKey != null) {
        final X509Certificate localCertChain[] = this.certChain != null ? this.certChain
                : new X509Certificate[] { (X509Certificate) cacert };
        final JcaX509CertificateHolder[] certificateHolderChain = CertTools
                .convertToX509CertificateHolder(localCertChain);
        gen.setRequestorName(certificateHolderChain[0].getSubject());
        req = gen.build(
                new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA")
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(this.signKey), 20480),
                certificateHolderChain);
    } else {
        req = gen.build();
    }
    // write request if directory exists.
    File ocspReqDir = new File(requestDirectory);
    if (ocspReqDir.isDirectory()) {
        OutputStream os = new FileOutputStream(new File(ocspReqDir, serialNr.toString()));
        os.write(req.getEncoded());
        os.close();
    }
    // Send the request and receive a BasicResponse
    return sendOCSPRequest(req.getEncoded(), cacert, useGet);
}

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

License:Open Source License

/** Tests ocsp message
 * @throws Exception error/*w  w w  .  j av  a 2 s .  co m*/
 */
@Test
public void test01OcspGood() throws Exception {
    log.trace(">test02OcspGood()");

    // And an OCSP request
    OCSPReqBuilder gen = new OCSPReqBuilder();
    final Certificate ocspTestCert = getTestCert();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), (X509Certificate) cacert,
            CertTools.getSerialNumber(ocspTestCert)));
    OCSPReq req = null;
    if (dosigning) {
        gen.setRequestorName(certChain[0].getSubject());
        req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder(signingAlg)
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privKey), 20480), certChain);
    } else {
        req = gen.build();
    }

    // Send the request and receive a singleResponse
    SingleResp singleResp = sendOCSPPost(req.getEncoded(), null);

    CertificateID certId = singleResp.getCertID();
    assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(),
            CertTools.getSerialNumber(ocspTestCert));
    Object status = singleResp.getCertStatus();
    assertEquals("Status is not null (good)", status, null);
    log.trace("<test02OcspGood()");
}

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

License:Open Source License

@Test
public void test07SignedOcsp() throws Exception {
    assertTrue("This test can only be run on a full EJBCA installation.",
            ((HttpURLConnection) new URL(httpReqPath + '/').openConnection()).getResponseCode() == 200);

    // find a CA (TestCA?) create a user and generate his cert
    // send OCSP req to server and get good response
    // change status of cert to bad status
    // send OCSP req and get bad status
    // (send crap message and get good error)
    try {/*from   w  w w  .  java  2s .c  om*/
        KeyPair keys = createUserCert(caid);

        // And an OCSP request
        OCSPReqBuilder gen = new OCSPReqBuilder();
        gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
                ocspTestCert.getSerialNumber()));
        Extension[] extensions = new Extension[1];
        extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
                new DEROctetString("123456789".getBytes()));
        gen.setRequestExtensions(new Extensions(extensions));

        X509CertificateHolder chain[] = new X509CertificateHolder[2];
        chain[0] = new JcaX509CertificateHolder(ocspTestCert);
        chain[1] = new JcaX509CertificateHolder(cacert);
        gen.setRequestorName(chain[0].getSubject());
        OCSPReq req = gen.build(new JcaContentSignerBuilder("SHA1WithRSA")
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keys.getPrivate()), chain);

        // First test with a signed OCSP request that can be verified
        Collection<Certificate> cacerts = new ArrayList<Certificate>();
        cacerts.add(cacert);
        CaCertificateCache certcache = CaCertificateCache.INSTANCE;
        certcache.loadCertificates(cacerts);
        X509Certificate signer = checkRequestSignature("127.0.0.1", req, certcache);
        assertNotNull(signer);
        assertEquals(ocspTestCert.getSerialNumber().toString(16), signer.getSerialNumber().toString(16));

        // Try with an unsigned request, we should get a SignRequestException
        req = gen.build();
        boolean caught = false;
        try {
            signer = checkRequestSignature("127.0.0.1", req, certcache);
        } catch (SignRequestException e) {
            caught = true;
        }
        assertTrue(caught);

        // sign with a keystore where the CA-certificate is not known
        KeyStore store = KeyStore.getInstance("PKCS12", "BC");
        ByteArrayInputStream fis = new ByteArrayInputStream(ks3);
        store.load(fis, "foo123".toCharArray());
        Certificate[] certs = KeyTools.getCertChain(store, "privateKey");
        chain[0] = new JcaX509CertificateHolder((X509Certificate) certs[0]);
        chain[1] = new JcaX509CertificateHolder((X509Certificate) certs[1]);
        PrivateKey pk = (PrivateKey) store.getKey("privateKey", "foo123".toCharArray());
        req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1WithRSA").build(pk), 20480),
                chain);
        // Send the request and receive a singleResponse, this response should
        // throw an SignRequestSignatureException
        caught = false;
        try {
            signer = checkRequestSignature("127.0.0.1", req, certcache);
        } catch (SignRequestSignatureException e) {
            caught = true;
        }
        assertTrue(caught);

        // sign with a keystore where the signing certificate has expired
        store = KeyStore.getInstance("PKCS12", "BC");
        fis = new ByteArrayInputStream(ksexpired);
        store.load(fis, "foo123".toCharArray());
        certs = KeyTools.getCertChain(store, "ocspclient");
        chain[0] = new JcaX509CertificateHolder((X509Certificate) certs[0]);
        chain[1] = new JcaX509CertificateHolder((X509Certificate) certs[1]);
        pk = (PrivateKey) store.getKey("ocspclient", "foo123".toCharArray());
        req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1WithRSA").build(pk), 20480),
                chain);
        // Send the request and receive a singleResponse, this response should
        // throw an SignRequestSignatureException
        caught = false;
        try {
            signer = checkRequestSignature("127.0.0.1", req, certcache);
        } catch (SignRequestSignatureException e) {
            caught = true;
        }
        assertTrue(caught);
    } finally {
        endEntityManagementSession.deleteUser(admin, "ocsptest");
    }

}

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

License:Open Source License

/** Tests ocsp message
 * @throws Exception error/*w  ww .j  av a2 s.  c o  m*/
 */
@Test
public void test01OcspGood() throws Exception {
    log.trace(">test01OcspGood()");

    // find a CA (TestCA?) create a user and generate his cert
    // send OCSP req to server and get good response
    // change status of cert to bad status
    // send OCSP req and get bad status
    // (send crap message and get good error)

    // Make user that we know...
    boolean userExists = endEntityManagementSession.existsUser(END_ENTITY_NAME);
    if (!userExists) {
        endEntityManagementSession.addUser(admin, END_ENTITY_NAME, "foo123", "C=SE,O=AnaTom,CN=OCSPTest", null,
                "ocsptest@anatom.se", false, SecConst.EMPTY_ENDENTITYPROFILE,
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, EndEntityTypes.ENDUSER.toEndEntityType(),
                SecConst.TOKEN_SOFT_PEM, 0, caid);
        log.debug("created user: ocsptest, foo123, C=SE, O=AnaTom, CN=OCSPTest");
    } else {
        log.debug("User ocsptest already exists.");
        EndEntityInformation userData = new EndEntityInformation(END_ENTITY_NAME, "C=SE,O=AnaTom,CN=OCSPTest",
                caid, null, "ocsptest@anatom.se", EndEntityConstants.STATUS_NEW,
                EndEntityTypes.ENDUSER.toEndEntityType(), SecConst.EMPTY_ENDENTITYPROFILE,
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, null, SecConst.TOKEN_SOFT_PEM, 0,
                null);
        userData.setPassword("foo123");
        endEntityManagementSession.changeUser(admin, userData, false);
        log.debug("Reset status to NEW");
    }
    try {
        // Generate certificate for the new user
        KeyPair keys = KeyTools.genKeys("512", "RSA");

        // user that we know exists...
        ocspTestCert = (X509Certificate) signSession.createCertificate(admin, "ocsptest", "foo123",
                new PublicKeyWrapper(keys.getPublic()));
        assertNotNull("Failed to create a certificate", ocspTestCert);

        // And an OCSP request
        OCSPReqBuilder gen = new OCSPReqBuilder();
        gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
                ocspTestCert.getSerialNumber()));
        Extension[] extensions = new Extension[1];
        extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
                new DEROctetString("123456789".getBytes()));
        gen.setRequestExtensions(new Extensions(extensions));
        X509CertificateHolder chain[] = new JcaX509CertificateHolder[2];
        chain[0] = new JcaX509CertificateHolder(ocspTestCert);
        chain[1] = new JcaX509CertificateHolder(cacert);
        gen.setRequestorName(chain[0].getSubject());
        OCSPReq req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA")
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keys.getPrivate()), 20480), chain);
        // Send the request and receive a singleResponse
        SingleResp[] singleResps = helper.sendOCSPPost(req.getEncoded(), "123456789",
                OCSPResponseStatus.SUCCESSFUL, 200);
        assertEquals("Number of of SingResps should be 1.", 1, singleResps.length);
        SingleResp singleResp = singleResps[0];

        CertificateID certId = singleResp.getCertID();
        assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(),
                ocspTestCert.getSerialNumber());
        Object status = singleResp.getCertStatus();
        assertEquals("Status is not null (good)", null, status);

        // Try with an unsigned request, we should get a status code 5 back from the server (signature required)
        req = gen.build();
        // Send the request and receive a singleResponse, this response should have error code SIGNATURE_REQUIRED
        singleResps = helper.sendOCSPPost(req.getEncoded(), "123456789", OCSPResponseStatus.SIG_REQUIRED, 200);
        assertNull(singleResps);

        // sign with a keystore where the CA-certificate is not known
        KeyStore store = KeyStore.getInstance("PKCS12", "BC");
        ByteArrayInputStream fis = new ByteArrayInputStream(ks3);
        store.load(fis, "foo123".toCharArray());
        Certificate[] certs = KeyTools.getCertChain(store, "privateKey");
        chain[0] = new JcaX509CertificateHolder((X509Certificate) certs[0]);
        chain[1] = new JcaX509CertificateHolder((X509Certificate) certs[1]);
        PrivateKey pk = (PrivateKey) store.getKey("privateKey", "foo123".toCharArray());
        req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA").build(pk), 20480),
                chain);
        // Send the request and receive a singleResponse, this response should have error code UNAUTHORIZED (6)
        singleResps = helper.sendOCSPPost(req.getEncoded(), "123456789", OCSPResponseStatus.UNAUTHORIZED, 200);
        assertNull(singleResps);
    } finally {
        endEntityManagementSession.deleteUser(roleMgmgToken, END_ENTITY_NAME);
    }
    log.trace("<test01OcspGood()");
}

From source file:org.jruby.ext.openssl.OCSPRequest.java

License:Common Public License

@JRubyMethod(name = "sign", rest = true)
public IRubyObject sign(final ThreadContext context, IRubyObject[] args) {
    final Ruby runtime = context.runtime;

    int flag = 0;
    IRubyObject additionalCerts = context.nil;
    IRubyObject flags = context.nil;/*from ww w. j  a  v a  2 s. c  om*/
    IRubyObject digest = context.nil;
    Digest digestInstance = new Digest(runtime, _Digest(runtime));
    IRubyObject nocerts = (RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOCERTS);

    switch (Arity.checkArgumentCount(runtime, args, 2, 5)) {
    case 3:
        additionalCerts = args[2];
        break;
    case 4:
        additionalCerts = args[2];
        flags = args[3];
        break;
    case 5:
        additionalCerts = args[2];
        flags = args[3];
        digest = args[4];
        break;
    default:
        break;

    }

    if (digest.isNil())
        digest = digestInstance.initialize(context,
                new IRubyObject[] { RubyString.newString(runtime, "SHA1") });
    if (additionalCerts.isNil())
        flag |= RubyFixnum.fix2int(nocerts);
    if (!flags.isNil())
        flag = RubyFixnum.fix2int(flags);

    X509Cert signer = (X509Cert) args[0];
    PKey signerKey = (PKey) args[1];

    String keyAlg = signerKey.getAlgorithm();
    String digAlg = ((Digest) digest).getShortAlgorithm();

    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(digAlg + "with" + keyAlg);
    signerBuilder.setProvider("BC");
    ContentSigner contentSigner = null;
    try {
        contentSigner = signerBuilder.build(signerKey.getPrivateKey());
    } catch (OperatorCreationException e) {
        throw newOCSPError(runtime, e);
    }

    OCSPReqBuilder builder = new OCSPReqBuilder();
    builder.setRequestorName(signer.getSubject().getX500Name());
    for (OCSPCertificateId certId : certificateIds) {
        builder.addRequest(new CertificateID(certId.getCertID()));
    }

    List<X509CertificateHolder> certChain = new ArrayList<X509CertificateHolder>();
    if (flag != RubyFixnum.fix2int(nocerts)) {
        try {
            certChain.add(new X509CertificateHolder(signer.getAuxCert().getEncoded()));
            if (!additionalCerts.isNil()) {
                Iterator<java.security.cert.Certificate> certIt = ((RubyArray) additionalCerts).iterator();
                while (certIt.hasNext()) {
                    certChain.add(new X509CertificateHolder(certIt.next().getEncoded()));
                }
            }
        } catch (Exception e) {
            throw newOCSPError(runtime, e);
        }
    }

    X509CertificateHolder[] chain = new X509CertificateHolder[certChain.size()];
    certChain.toArray(chain);

    try {
        asn1bcReq = org.bouncycastle.asn1.ocsp.OCSPRequest
                .getInstance(builder.build(contentSigner, chain).getEncoded());
    } catch (Exception e) {
        throw newOCSPError(runtime, e);
    }

    if (nonce != null) {
        addNonceImpl();
    }

    return this;
}