Example usage for org.bouncycastle.asn1 DEROctetString DEROctetString

List of usage examples for org.bouncycastle.asn1 DEROctetString DEROctetString

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 DEROctetString DEROctetString.

Prototype

public DEROctetString(ASN1Encodable obj) throws IOException 

Source Link

Document

Constructor from the encoding of an ASN.1 object.

Usage

From source file:org.ejbca.core.protocol.ocsp.extension.unid.OCSPUnidExtension.java

License:Open Source License

@Override
public Map<ASN1ObjectIdentifier, Extension> process(X509Certificate[] requestCertificates, String remoteAddress,
        String remoteHost, X509Certificate cert, CertificateStatus status) {
    if (m_log.isTraceEnabled()) {
        m_log.trace(">process()");
    }// w  w  w.j a va  2  s .  co  m
    // Check authorization first
    if (!checkAuthorization(requestCertificates, remoteAddress, remoteHost)) {
        errCode = OCSPUnidExtension.ERROR_UNAUTHORIZED;
        return null;
    }
    // If the certificate is revoked, we must not return an FNR
    if (status != null) {
        errCode = OCSPUnidExtension.ERROR_CERT_REVOKED;
        return null;
    }
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet result = null;
    String fnr = null;
    String sn = null;
    try {
        // The Unis is in the DN component serialNumber
        sn = CertTools.getPartFromDN(cert.getSubjectDN().getName(), "SN");
        if (sn != null) {
            if (m_log.isDebugEnabled()) {
                m_log.debug("Found serialNumber: " + sn);
            }
            String iMsg = intres.getLocalizedMessage("ocsp.receivedunidreq", remoteAddress, remoteHost, sn);
            m_log.info(iMsg);
            try {
                con = ServiceLocator.getInstance().getDataSource(dataSourceJndi).getConnection();
            } catch (SQLException e) {
                String errMsg = intres.getLocalizedMessage("ocsp.errordatabaseunid");
                m_log.error(errMsg, e);
                errCode = OCSPUnidExtension.ERROR_SERVICE_UNAVAILABLE;
                return null;
            }
            ps = con.prepareStatement("select fnr from UnidFnrMapping where unid=?");
            ps.setString(1, sn);
            result = ps.executeQuery();
            if (result.next()) {
                fnr = result.getString(1);
            }
        } else {
            String errMsg = intres.getLocalizedMessage("ocsp.errorunidnosnindn", cert.getSubjectDN().getName());
            m_log.error(errMsg);
            errCode = OCSPUnidExtension.ERROR_NO_SERIAL_IN_DN;
            return null;
        }
        m_log.trace("<process()");
    } catch (Exception e) {
        throw new EJBException(e);
    } finally {
        JDBCUtil.close(con, ps, result);
    }

    // Construct the response extentsion if we found a mapping
    if (fnr == null) {
        String errMsg = intres.getLocalizedMessage("ocsp.errorunidnosnmapping", sn);
        m_log.error(errMsg);
        errCode = OCSPUnidExtension.ERROR_NO_FNR_MAPPING;
        return null;

    }
    String errMsg = intres.getLocalizedMessage("ocsp.returnedunidresponse", remoteAddress, remoteHost, fnr, sn);
    m_log.info(errMsg);
    FnrFromUnidExtension ext = new FnrFromUnidExtension(fnr);
    HashMap<ASN1ObjectIdentifier, Extension> ret = new HashMap<ASN1ObjectIdentifier, Extension>();
    try {
        ret.put(FnrFromUnidExtension.FnrFromUnidOid,
                new Extension(FnrFromUnidExtension.FnrFromUnidOid, false, new DEROctetString(ext)));
    } catch (IOException e) {
        throw new IllegalStateException("Unexpected IOException caught.", e);
    }
    return ret;
}

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

License:Open Source License

private void verifyStatus(int caid, X509Certificate cacert, BigInteger certSerial, int ocspResponseStatus,
        Status expectedStatus, int expectedReason, Date expectedRevTime) throws NoSuchProviderException,
        IOException, OCSPException, OperatorCreationException, CertificateException {
    // And an OCSP request
    final OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, certSerial));
    log.debug("ocspTestCert.getSerialNumber() = " + certSerial);
    final String sNonce = "123456789";
    Extension[] extensions = new Extension[1];
    extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
            new DEROctetString(sNonce.getBytes()));
    gen.setRequestExtensions(new Extensions(extensions));

    final OCSPReq req = gen.build();

    // Send the request and receive a singleResponse
    final SingleResp[] singleResps = sendOCSPPost(req.getEncoded(), sNonce, ocspResponseStatus, 200);
    // if we expected internal error, we should not expect any data, and can not make any more tests
    if (ocspResponseStatus == OCSPRespBuilder.INTERNAL_ERROR) {
        return;/*from   w w  w  .  j  av a 2s .c  o m*/
    }

    if (ocspResponseStatus == OCSPRespBuilder.UNAUTHORIZED) {
        return;
    }
    assertEquals("No of SingleResps should be 1.", 1, singleResps.length);
    final SingleResp singleResp = singleResps[0];

    final CertificateID certId = singleResp.getCertID();
    assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), certSerial);
    final Object status = singleResp.getCertStatus();
    final String statusClassName = status != null ? status.getClass().getName() : "GOOD";// status==null means GOOD
    switch (expectedStatus) {
    case Unknown:
        assertTrue("Status is not Unknown: " + statusClassName, status instanceof UnknownStatus);
        break;
    case Good:
        if (status != CertificateStatus.GOOD) {
            log.debug("Certificate status: " + status.getClass().getName());
        }
        assertEquals("Status is not Good, was: " + statusClassName + ".", CertificateStatus.GOOD, status);
        break;
    case Revoked:
        assertTrue("Status is not Revoked: " + statusClassName, status instanceof RevokedStatus);
        final int reason = ((RevokedStatus) status).getRevocationReason();
        assertEquals("Wrong revocation reason", expectedReason, reason);
        if (expectedRevTime != null) {
            final Date revTime = ((RevokedStatus) status).getRevocationTime();
            assertEquals("Wrong revocation time", expectedRevTime, revTime);
        }
        break;
    }
}

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

License:Open Source License

/**
 * @param keystore KeyStore client keystore used to authenticate TLS client authentication, or null if TLS is not used
 * @param pwd String password for the key store, or null if no keystore is used
 * @param ocspurl String url to the OCSP server, or null if we should try to use the AIA extension from the cert; e.g. http://127.0.0.1:8080/ejbca/publicweb/status/ocsp (or https for TLS)
 * @param certs certificate chain to signing key
 * @param _signKey signing key//from   www .  j a  v  a  2 s.c o m
 * @param getfnr true if FNR should be fetched
 * @throws NoSuchAlgorithmException
 * @throws IOException if ASN1 parsing error occurs
 */
private OCSPUnidClient(KeyStore keystore, String pwd, String ocspurl, Certificate[] certs, PrivateKey _signKey,
        boolean getfnr) throws NoSuchAlgorithmException, IOException {
    this.httpReqPath = ocspurl;
    this.passphrase = pwd;
    this.ks = keystore;
    this.signKey = _signKey;
    this.certChain = certs != null ? Arrays.asList(certs).toArray(new X509Certificate[0]) : null;
    this.nonce = new byte[16];
    {
        List<Extension> extensionList = new ArrayList<Extension>();
        final Random randomSource = new Random();
        randomSource.nextBytes(nonce);
        extensionList
                .add(new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce)));
        // Don't bother adding Unid extension if we are not using client authentication
        if (getfnr) {
            extensionList.add(new Extension(FnrFromUnidExtension.FnrFromUnidOid, false,
                    new DEROctetString(new FnrFromUnidExtension("1"))));
        }
        extensions = new Extensions(extensionList.toArray(new Extension[extensionList.size()]));
    }
    CryptoProviderTools.installBCProviderIfNotAvailable();
}

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

License:Open Source License

/** Called by OCSP responder when the configured extension is found in the request.
 * //  w w  w  . j  a v  a  2s.  com
 * @param request HttpServletRequest that can be used to find out information about caller, TLS certificate etc.
 * @param cert X509Certificate the caller asked for in the OCSP request
  * @param status CertificateStatus the status the certificate has according to the OCSP responder, null means the cert is good
 * @return X509Extension that will be added to responseExtensions by OCSP responder, or null if an error occurs
 */
public Hashtable process(HttpServletRequest request, X509Certificate cert, CertificateStatus status) {
    if (m_log.isTraceEnabled()) {
        m_log.trace(">process()");
    }
    // Check authorization first
    if (!checkAuthorization(request)) {
        errCode = OCSPUnidExtension.ERROR_UNAUTHORIZED;
        return null;
    }
    // If the certificate is revoked, we must not return an FNR
    if (status != null) {
        errCode = OCSPUnidExtension.ERROR_CERT_REVOKED;
        return null;
    }
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet result = null;
    String fnr = null;
    String sn = null;
    try {
        // The Unis is in the DN component serialNumber
        sn = CertTools.getPartFromDN(cert.getSubjectDN().getName(), "SN");
        if (sn != null) {
            if (m_log.isDebugEnabled()) {
                m_log.debug("Found serialNumber: " + sn);
            }
            String iMsg = intres.getLocalizedMessage("ocsp.receivedunidreq", request.getRemoteAddr(),
                    request.getRemoteHost(), sn);
            m_log.info(iMsg);
            try {
                con = ServiceLocator.getInstance().getDataSource(dataSourceJndi).getConnection();
            } catch (SQLException e) {
                String errMsg = intres.getLocalizedMessage("ocsp.errordatabaseunid");
                m_log.error(errMsg, e);
                errCode = OCSPUnidExtension.ERROR_SERVICE_UNAVAILABLE;
                return null;
            }
            ps = con.prepareStatement("select fnr from UnidFnrMapping where unid=?");
            ps.setString(1, sn);
            result = ps.executeQuery();
            if (result.next()) {
                fnr = result.getString(1);
            }
        } else {
            String errMsg = intres.getLocalizedMessage("ocsp.errorunidnosnindn", cert.getSubjectDN().getName());
            m_log.error(errMsg);
            errCode = OCSPUnidExtension.ERROR_NO_SERIAL_IN_DN;
            return null;
        }
        m_log.trace("<process()");
    } catch (Exception e) {
        throw new EJBException(e);
    } finally {
        JDBCUtil.close(con, ps, result);
    }

    // Construct the response extentsion if we found a mapping
    if (fnr == null) {
        String errMsg = intres.getLocalizedMessage("ocsp.errorunidnosnmapping", sn);
        m_log.error(errMsg);
        errCode = OCSPUnidExtension.ERROR_NO_FNR_MAPPING;
        return null;

    }
    String errMsg = intres.getLocalizedMessage("ocsp.returnedunidresponse", request.getRemoteAddr(),
            request.getRemoteHost(), fnr, sn);
    m_log.info(errMsg);
    FnrFromUnidExtension ext = new FnrFromUnidExtension(fnr);
    Hashtable ret = new Hashtable();
    ret.put(FnrFromUnidExtension.FnrFromUnidOid, new X509Extension(false, new DEROctetString(ext)));
    return ret;
}

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

License:Open Source License

public void test01CreateOCSPCAServiceResponse() throws Exception {
    KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
    ks.load(new ByteArrayInputStream(sceprap12), "foo123".toCharArray());
    String providerName = "BC";
    X509Certificate racert = (X509Certificate) ks.getCertificate("Scep RA");
    Certificate[] chain = ks.getCertificateChain("Scep RA");
    assertEquals(3, chain.length);//from   w  ww.ja v a  2s .  c  o  m
    X509Certificate cacert = (X509Certificate) chain[1];
    String signer = CertTools.getSubjectDN(chain[0]);
    assertEquals("CN=Scep RA,O=PrimeKey,C=SE", signer);
    PrivateKey privKey = (PrivateKey) ks.getKey("Scep RA", "foo123".toCharArray());
    X509Certificate[] certChain = new X509Certificate[chain.length];
    for (int i = 0; i < chain.length; i++) {
        certChain[i] = (X509Certificate) chain[i];
    }
    // Everything looks OK, lets get started with the real tests.

    // An OCSP request
    OCSPReqGenerator gen = new OCSPReqGenerator();
    gen.addRequest(new CertificateID(CertificateID.HASH_SHA1, cacert, racert.getSerialNumber()));
    Hashtable exts = new Hashtable();
    X509Extension ext = new X509Extension(false, new DEROctetString("123456789".getBytes()));
    exts.put(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, ext);
    gen.setRequestExtensions(new X509Extensions(exts));
    OCSPReq req = gen.generate();

    // A response to create
    ArrayList responseList = new ArrayList();
    CertificateID certId = req.getRequestList()[0].getCertID();
    responseList.add(new OCSPResponseItem(certId, new UnknownStatus(), 0));

    // First check that the whole chain is included and the responderId is keyHash
    OCSPCAServiceRequest ocspServiceReq = new OCSPCAServiceRequest(req, responseList, null,
            "SHA1WithRSA;SHA1WithDSA;SHA1WithECDSA", true);
    ocspServiceReq.setRespIdType(OcspConfiguration.RESPONDERIDTYPE_KEYHASH);

    OCSPCAServiceResponse response = OCSPUtil.createOCSPCAServiceResponse(ocspServiceReq, privKey, providerName,
            certChain);
    BasicOCSPResp basicResp = response.getBasicOCSPResp();
    X509Certificate[] respCerts = basicResp.getCerts("BC");
    assertEquals(3, respCerts.length); // Certificate chain included
    RespID respId = basicResp.getResponderId();
    RespID testKeyHash = new RespID(racert.getPublicKey());
    RespID testName = new RespID(racert.getSubjectX500Principal());
    assertEquals(respId, testKeyHash);
    assertFalse(respId.equals(testName));

    // Second check that the whole chain is NOT included and the responderId is Name
    ocspServiceReq = new OCSPCAServiceRequest(req, responseList, null, "SHA1WithRSA;SHA1WithDSA;SHA1WithECDSA",
            false);
    ocspServiceReq.setRespIdType(OcspConfiguration.RESPONDERIDTYPE_NAME);
    response = OCSPUtil.createOCSPCAServiceResponse(ocspServiceReq, privKey, providerName, certChain);
    basicResp = response.getBasicOCSPResp();
    respCerts = basicResp.getCerts("BC");
    assertEquals(1, respCerts.length); // Certificate chain included
    respId = basicResp.getResponderId();
    assertFalse(respId.equals(testKeyHash));
    assertEquals(respId, testName);

    // Third do some verification
    basicResp.verify(racert.getPublicKey(), "BC");
    SingleResp[] responses = basicResp.getResponses();
    assertEquals(1, responses.length);
    SingleResp resp = responses[0];
    CertificateID myid = resp.getCertID();
    assertEquals(certId, myid);
}

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

License:Open Source License

/**
 * Tests ocsp message with good status and a valid unid
 * //from  w ww . ja v  a2s .c  om
 * @throws Exception error
 */
@Test
public void test01OcspGoodWithFnr() throws Exception {
    // Make user that we know...
    boolean userExists = false;
    try {
        endEntityManagementSession.addUser(admin, "unidtest", "foo123",
                "C=SE,O=AnaTom,surname=Jansson,serialNumber=123456789,CN=UNIDTest", null, "unidtest@anatom.se",
                false, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER,
                EndEntityTypes.ENDUSER.toEndEntityType(), SecConst.TOKEN_SOFT_PEM, 0, caid);
        log.debug(
                "created user: unidtest, foo123, C=SE, O=AnaTom,surname=Jansson,serialNumber=123456789, CN=UNIDTest");
    } catch (EndEntityExistsException e) {
        userExists = true;
    }
    if (userExists) {
        log.debug("User unidtest already exists.");
        EndEntityInformation userData = new EndEntityInformation("unidtest",
                "C=SE,O=AnaTom,surname=Jansson,serialNumber=123456789,CN=UNIDTest", caid, null,
                "unidtest@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");
    }
    // Generate certificate for the new user

    // user that we know exists...
    ocspTestCert = (X509Certificate) signSession.createCertificate(admin, "unidtest", "foo123",
            new PublicKeyWrapper(keys.getPublic()));
    assertNotNull("Failed to create 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(FnrFromUnidExtension.FnrFromUnidOid, false,
            new DEROctetString("123456789".getBytes()));
    gen.setRequestExtensions(new Extensions(extensions));

    OCSPReq req = gen.build();

    // Send the request and receive a BasicResponse
    BasicOCSPResp brep = sendOCSPPost(req.getEncoded(), true);
    assertEquals(getFnr(brep), "654321");
    SingleResp[] singleResps = brep.getResponses();
    assertEquals("No of SingResps should be 1.", singleResps.length, 1);
    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)", status, null);
}

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

License:Open Source License

/**
 * Tests ocsp message with bad status and a valid unid
 * /*from w w  w  .  jav a  2s  .co  m*/
 * @throws Exception error
 */
@Test
public void test02OcspBadWithFnr() throws Exception {
    revocationSession.revokeCertificate(admin, ocspTestCert, null,
            RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE, null);

    // 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(FnrFromUnidExtension.FnrFromUnidOid, false,
            new DEROctetString("123456789".getBytes()));
    gen.setRequestExtensions(new Extensions(extensions));
    OCSPReq req = gen.build();

    // Send the request and receive a BasicResponse
    BasicOCSPResp brep = sendOCSPPost(req.getEncoded(), true);
    // When a certificate is revoked the FNR must not be returned
    assertEquals(getFnr(brep), null);
    SingleResp[] singleResps = brep.getResponses();
    assertEquals("No of SingResps should be 1.", singleResps.length, 1);
    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();
    assertTrue("Status is not RevokedStatus", status instanceof RevokedStatus);
    RevokedStatus rev = (RevokedStatus) status;
    assertTrue("Status does not have reason", rev.hasRevocationReason());
    int reason = rev.getRevocationReason();
    assertEquals("Wrong revocation reason", reason, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE);
}

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

License:Open Source License

/**
 * Tests ocsp message with good status and invalid unid
 * //from  w  w w . ja  va 2  s .c om
 * @throws Exception error
 */
@Test
public void test03OcspGoodWithNoFnr() throws Exception {
    // Change uses to a Unid that we don't have mapping for
    EndEntityInformation userData = new EndEntityInformation("unidtest",
            "C=SE,O=AnaTom,surname=Jansson,serialNumber=123456789,CN=UNIDTest", caid, null,
            "unidtest@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");
    // Generate certificate for the new/changed user
    ocspTestCert = (X509Certificate) signSession.createCertificate(admin, "unidtest", "foo123",
            new PublicKeyWrapper(keys.getPublic()));
    assertNotNull("Failed to create 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(FnrFromUnidExtension.FnrFromUnidOid, false,
            new DEROctetString("123456789".getBytes()));
    gen.setRequestExtensions(new Extensions(extensions));
    OCSPReq req = gen.build();

    // Send the request and receive a BasicResponse
    BasicOCSPResp brep = sendOCSPPost(req.getEncoded(), true);
    assertEquals(getFnr(brep), null);
    SingleResp[] singleResps = brep.getResponses();
    assertEquals("No of SingResps should be 1.", singleResps.length, 1);
    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)", status, null);
}

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

License:Open Source License

/**
 * Tests ocsp message with good status but no serialNnumber in the DN
 * /*from w w  w  . j  av  a2s .c  om*/
 * @throws Exception error
 */
@Test
public void test04OcspGoodNoSerialNo() throws Exception {
    // Change uses to not have any serialNumber
    EndEntityInformation userData = new EndEntityInformation("unidtest",
            "C=SE,O=AnaTom,surname=Jansson,serialNumber=123456789,CN=UNIDTest", caid, null,
            "unidtest@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");
    // Generate certificate for the new/changed user
    ocspTestCert = (X509Certificate) signSession.createCertificate(admin, "unidtest", "foo123",
            new PublicKeyWrapper(keys.getPublic()));
    assertNotNull("Failed to create 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(FnrFromUnidExtension.FnrFromUnidOid, false,
            new DEROctetString("123456789".getBytes()));
    gen.setRequestExtensions(new Extensions(extensions));
    OCSPReq req = gen.build();

    // Send the request and receive a BasicResponse
    BasicOCSPResp brep = sendOCSPPost(req.getEncoded(), true);
    assertEquals(getFnr(brep), null);
    SingleResp[] singleResps = brep.getResponses();
    assertEquals("No of SingResps should be 1.", singleResps.length, 1);
    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)", status, null);
}

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

License:Open Source License

/**
 * test a lookup message from an untrusted requestor, should not work
 * //  w w  w  . jav a  2s .  c  om
 * @throws Exception
 */
@Test
public void test05HttpsNotAuthorized() throws Exception {
    // Change uses to a Unid that is OK
    EndEntityInformation userData = new EndEntityInformation("unidtest",
            "C=SE,O=AnaTom,surname=Jansson,serialNumber=123456789,CN=UNIDTest", caid, null,
            "unidtest@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");
    userData.setStatus(EndEntityConstants.STATUS_NEW);
    endEntityManagementSession.changeUser(admin, userData, false);
    log.debug("Reset status to NEW");
    // Generate certificate for the new/changed user
    ocspTestCert = (X509Certificate) signSession.createCertificate(admin, "unidtest", "foo123",
            new PublicKeyWrapper(keys.getPublic()));
    assertNotNull("Failed to create 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(FnrFromUnidExtension.FnrFromUnidOid, false,
            new DEROctetString("123456789".getBytes()));
    gen.setRequestExtensions(new Extensions(extensions));
    OCSPReq req = gen.build();

    // Send the request and receive a BasicResponse
    BasicOCSPResp brep = sendOCSPPost(req.getEncoded(), false);
    assertEquals(getFnr(brep), null);
    SingleResp[] singleResps = brep.getResponses();
    assertEquals("No of SingResps should be 1.", singleResps.length, 1);
    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)", status, null);
}