Example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers sha1WithRSAEncryption

List of usage examples for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers sha1WithRSAEncryption

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers sha1WithRSAEncryption.

Prototype

ASN1ObjectIdentifier sha1WithRSAEncryption

To view the source code for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers sha1WithRSAEncryption.

Click Source Link

Document

PKCS#1: 1.2.840.113549.1.1.5

Usage

From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessageTest.java

License:Open Source License

@Test
public void testNovosecClientRequestSHA1() throws IOException, InvalidKeyException, NoSuchAlgorithmException,
        NoSuchProviderException, InvalidAlgorithmParameterException, SignatureException, IllegalStateException,
        OperatorCreationException, CertificateException {
    doNovosecClientRequest("SHA1WithRSA", CMSSignedGenerator.DIGEST_SHA1,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
}

From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessageTest.java

License:Open Source License

private void doNovosecClientRequest(final String sigAlg, final String digestAlg, final String expectedAlgOid)
        throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException,
        InvalidAlgorithmParameterException, SignatureException, IllegalStateException,
        OperatorCreationException, CertificateException {
    // Check that we can parse a request from  Novosec (patched by EJBCA).
    // Read an initialization request with a signature POP and signature protection to see that we can process it
    {//w ww . ja v  a 2  s .  com
        ASN1InputStream in = new ASN1InputStream(novosecsigpopir);
        try {
            ASN1Primitive derObject = in.readObject();
            PKIMessage req = PKIMessage.getInstance(derObject);
            //log.info(req.toString());
            // Verify should be ok if we do not allow RA verify POP here
            CrmfRequestMessage msg = new CrmfRequestMessage(req, "CN=AdminCA1", false, "CN");
            assertTrue(msg.verify());
            // Since we don't have RA POP we can't test for that...
            assertEquals("CN=AdminCA1,O=EJBCA Sample,C=SE", msg.getIssuerDN());
            assertEquals("CN=abc123rry2942812801980668853,O=PrimeKey Solutions AB,C=SE", msg.getRequestDN());
            assertEquals("abc123rry2942812801980668853", msg.getUsername());
            assertEquals("foo123", msg.getPassword());
            // Verify signature protection
            AlgorithmIdentifier algId = msg.getMessage().getHeader().getProtectionAlg();
            String oid = algId.getAlgorithm().getId();
            assertEquals(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), oid);
            // Check that this is an old message, created before ECA-2104, using null instead of DERNull as algorithm parameters.
            ASN1Encodable pp = algId.getParameters();
            assertNull(pp);
            // Try to verify, it should work good even though the small bug in ECA-2104, since we don't use algorithm parameters for RSA-PKCS signatures
            PublicKey pubKey = msg.getRequestPublicKey();
            assertTrue(CmpMessageHelper.verifyCertBasedPKIProtection(msg.getMessage(), pubKey));
            // Verify that our verification routine does not give positive result for any other keys
            KeyPair keys = KeyTools.genKeys("512", "RSA");
            assertFalse(CmpMessageHelper.verifyCertBasedPKIProtection(msg.getMessage(), keys.getPublic()));
        } finally {
            in.close();
        }
    }
    // Re-protect the message, now fixed by ECA-2104
    {
        ASN1InputStream in = new ASN1InputStream(novosecsigpopir);
        try {
            ASN1Primitive derObject = in.readObject();
            PKIMessage myPKIMessage = PKIMessage.getInstance(derObject);
            KeyPair keys = KeyTools.genKeys("512", "RSA");
            X509Certificate signCert = CertTools.genSelfCert("CN=CMP Sign Test", 3650, null, keys.getPrivate(),
                    keys.getPublic(), sigAlg, false);
            // Re-sign the message
            Collection<Certificate> signCertChain = new ArrayList<Certificate>();
            signCertChain.add(signCert);
            byte[] newmsg = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, keys.getPrivate(),
                    digestAlg, "BC");
            in.close();
            in = new ASN1InputStream(newmsg);
            derObject = in.readObject();
            PKIMessage pkimsg = PKIMessage.getInstance(derObject);
            // We have to do this twice, because Novosec caches ProtectedBytes in the PKIMessage object, so we need to 
            // encode it and re-decode it again to get the changes from ECA-2104 encoded correctly.
            // Not needed when simply signing a new message that you create, only when re-signing 
            newmsg = CmpMessageHelper.signPKIMessage(pkimsg, signCertChain, keys.getPrivate(), digestAlg, "BC");
            in.close();
            in = new ASN1InputStream(newmsg);
            derObject = in.readObject();
            pkimsg = PKIMessage.getInstance(derObject);
            AlgorithmIdentifier algId = pkimsg.getHeader().getProtectionAlg();
            String oid = algId.getAlgorithm().getId();
            assertEquals(expectedAlgOid, oid);
            // Check that we have DERNull and not plain java null as algorithm parameters.
            ASN1Encodable pp = algId.getParameters();
            assertNotNull(pp);
            assertEquals(DERNull.class.getName(), pp.getClass().getName());
            // Try to verify, also verify at the same time that encoding decoding of the signature works
            assertTrue(CmpMessageHelper.verifyCertBasedPKIProtection(pkimsg, keys.getPublic()));
            // Verify that our verification routine does not give positive result for any other keys
            CrmfRequestMessage msg = new CrmfRequestMessage(pkimsg, "CN=AdminCA1", false, "CN");
            assertTrue(msg.verify());
            PublicKey pubKey = msg.getRequestPublicKey();
            assertFalse(CmpMessageHelper.verifyCertBasedPKIProtection(pkimsg, pubKey));
        } finally {
            in.close();
        }
    }
}

From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessageTest.java

License:Open Source License

private void internalBcClientRequestTest(byte[] message) throws IOException, InvalidKeyException,
        NoSuchAlgorithmException, NoSuchProviderException, SignatureException {
    // Check that we can parse request from BouncyCastle version 1.46.       
    // Read an initialization request with a signature POP, and signature protection, to see that we can process it
    ASN1InputStream in = new ASN1InputStream(message);
    try {/*from  w  w w . ja v a 2s .c o m*/
        ASN1Primitive derObject = in.readObject();
        PKIMessage req = PKIMessage.getInstance(derObject);
        //log.info(req.toString());
        // Verify should be ok if we do not allow RA verify POP here
        CrmfRequestMessage msg = new CrmfRequestMessage(req, "CN=AdminCA1", false, "CN");
        // BC messages in BC1.46 uses POPOSigningKeyInput for POPO, not the 3rd case in RFC4211 section 4.1, like everyone else...
        // BC messages in BC1.47 should use normal POPO, 3rd case
        assertTrue(msg.verify());
        // Since we don't have RA POP we can't test for that...
        assertEquals("CN=AdminCA1", msg.getIssuerDN());
        assertEquals("CN=user", msg.getRequestDN());
        assertEquals("user", msg.getUsername());
        assertEquals("foo123", msg.getPassword());
        // Check signature protection
        AlgorithmIdentifier algId = msg.getMessage().getHeader().getProtectionAlg();
        String oid = algId.getAlgorithm().getId();
        assertEquals(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), oid);
        // Check that we have DERNull and not plain java null as algorithm parameters.
        ASN1Encodable pp = algId.getParameters();
        assertNotNull(pp);
        assertEquals(DERNull.class.getName(), pp.getClass().getName());
        // Try to verify the protection signature
        assertTrue(CmpMessageHelper.verifyCertBasedPKIProtection(msg.getMessage(), msg.getRequestPublicKey()));
    } finally {
        in.close();
    }
}

From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessageTest.java

License:Open Source License

@Test
public void testHuaweiEnodeBClientRequest() throws IOException, InvalidKeyException, NoSuchAlgorithmException,
        NoSuchProviderException, SignatureException {
    // Read an initialization request to see that we can process it
    ASN1InputStream in = new ASN1InputStream(huaweiir);
    try {//from  w  w w .  j ava2  s.  c  o m
        ASN1Primitive derObject = in.readObject();
        PKIMessage req = PKIMessage.getInstance(derObject);
        //log.info(req.toString());
        CrmfRequestMessage msg = new CrmfRequestMessage(req, null, false, "CN");
        // This message does not have an issuerDN in the cert template
        assertNull(msg.getIssuerDN());
        // Use a default CA instead
        msg = new CrmfRequestMessage(req, "CN=AdminCA1", false, "CN");
        assertTrue(msg.verify());
        assertEquals("CN=AdminCA1", msg.getIssuerDN());
        assertEquals("CN=21030533610000000012 eNodeB", msg.getRequestDN());
        assertEquals("21030533610000000012 eNodeB", msg.getUsername());
        // We would like a password here...
        assertNull(msg.getPassword());
        AlgorithmIdentifier algId = msg.getMessage().getHeader().getProtectionAlg();
        String oid = algId.getAlgorithm().getId();
        assertEquals(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), oid);
        // Check that we have DERNull and not plain java null as algorithm parameters.
        ASN1Encodable pp = algId.getParameters();
        assertNotNull(pp);
        assertEquals(DERNull.class.getName(), pp.getClass().getName());
        // Try to verify message protection
        // Does not work for this Huawei message, is it signed by the same key as in the request at all?
        // We will wait for another huawei message to test
        //PublicKey pubKey = msg.getRequestPublicKey();
        //assertTrue(CmpMessageHelper.verifyCertBasedPKIProtection(msg.getMessage(), pubKey));

        // Read the CertConf (certificate confirmation) CMP message that the client sends to
        // the CA after receiving the certificate. RFC4210 section "5.3.18.  Certificate Confirmation Content".
        in.close();
        in = new ASN1InputStream(huaweicertconf);
        derObject = in.readObject();
        PKIMessage certconf = PKIMessage.getInstance(derObject);
        //log.info(certconf.toString());
        GeneralCmpMessage conf = new GeneralCmpMessage(certconf);
        algId = conf.getMessage().getHeader().getProtectionAlg();
        oid = algId.getAlgorithm().getId();
        assertEquals(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), oid);
        // Check that we have DERNull and not plain java null as algorithm parameters.
        pp = algId.getParameters();
        assertNotNull(pp);
        assertEquals(DERNull.class.getName(), pp.getClass().getName());
        // Try to verify message protection
        // Does not work for this Huawei message, is it signed by the same key as in the request at all?
        // We will wait for another huawei message to test
        //PublicKey pubKey = msg.getRequestPublicKey();
        //assertTrue(CmpMessageHelper.verifyCertBasedPKIProtection(msg.getMessage(), pubKey));
    } finally {
        in.close();
    }
}

From source file:org.ejbca.core.protocol.cmp.CrmfRequestTest.java

License:Open Source License

@Test
public void test01CrmfHttpUnknowUser() throws Exception {
    log.trace(">test01CrmfHttpUnknowUser");
    // A name that does not exist
    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    // USER_DN = USER_DN + ", serialNumber=01234567";
    PKIMessage req = genCertReq(ISSUER_DN, USER_DN, this.keys, this.cacert, nonce, transid, false, null, null,
            null, null, null, null);/*  w w w  .  j  a  v a  2s. co  m*/
    assertNotNull(req);
    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();

    byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
    checkCmpResponseGeneral(resp, ISSUER_DN, USER_DN, this.cacert, nonce, transid, true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpFailMessage(resp, "Wrong username or password", 1, reqId, 7, PKIFailureInfo.incorrectData); // Expects a CertificateResponse (reject) message with error
    // FailInfo.INCORRECT_DATA
    log.trace("<test01CrmfHttpUnknowUser");
}

From source file:org.ejbca.core.protocol.cmp.CrmfRequestTest.java

License:Open Source License

@Test
public void test02CrmfHttpUnknowUserSignedMessage() throws Exception {
    // A name that does not exist
    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIMessage req = genCertReq(ISSUER_DN, USER_DN, this.keys, this.cacert, nonce, transid, false, null, null,
            null, null, null, null);/*from   w  w  w  . j  a  v a 2s.c om*/
    assertNotNull(req);
    X509Certificate signCert = CertTools.genSelfCert("CN=CMP Sign Test", 3650, null, this.keys.getPrivate(),
            this.keys.getPublic(), "SHA256WithRSA", false);
    ArrayList<Certificate> signCertColl = new ArrayList<Certificate>();
    signCertColl.add(signCert);
    CmpMessageHelper.signPKIMessage(req, signCertColl, this.keys.getPrivate(), CMSSignedGenerator.DIGEST_SHA1,
            "BC");
    // PKIMessage req = protectPKIMessage(req1, false, "foo123", "mykeyid", 567);
    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
    checkCmpResponseGeneral(resp, ISSUER_DN, USER_DN, this.cacert, nonce, transid, true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpFailMessage(resp, "Wrong username or password", 1, reqId, 7, PKIFailureInfo.incorrectData); // Expects a CertificateResponse (reject) message with error
    // FailInfo.INCORRECT_DATA
}

From source file:org.ejbca.core.protocol.cmp.CrmfRequestTest.java

License:Open Source License

@Test
public void test03CrmfHttpOkUser() throws Exception {
    log.trace(">test03CrmfHttpOkUser");
    // Create a new good USER
    final X500Name userDN = createCmpUser("cmptest", "C=SE,O=PrimeKey,CN=cmptest", true);

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIMessage req = genCertReq(ISSUER_DN, userDN, this.keys, this.cacert, nonce, transid, false, null, null,
            null, null, null, null);//from   ww w .  ja  v a  2 s  . c  o m
    assertNotNull(req);
    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
    checkCmpResponseGeneral(resp, ISSUER_DN, userDN, this.cacert, nonce, transid, true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
    String altNames = CertTools.getSubjectAlternativeName(cert);
    assertNull("AltNames was not null (" + altNames + ").", altNames);

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(userDN, this.cacert, nonce, transid, hash, reqId);
    assertNotNull(confirm);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(confirm);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, cmpAlias);
    checkCmpResponseGeneral(resp, ISSUER_DN, userDN, this.cacert, nonce, transid, false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIConfirmMessage(userDN, this.cacert, resp);

    // Now revoke the bastard!
    PKIMessage rev = genRevReq(ISSUER_DN, userDN, cert.getSerialNumber(), this.cacert, nonce, transid, true,
            null, null);
    assertNotNull(rev);
    ByteArrayOutputStream baorev = new ByteArrayOutputStream();
    DEROutputStream outrev = new DEROutputStream(baorev);
    outrev.writeObject(rev);
    byte[] barev = baorev.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(barev, 200, cmpAlias);
    checkCmpResponseGeneral(resp, ISSUER_DN, userDN, this.cacert, nonce, transid, false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpFailMessage(resp, "PKI Message is not athenticated properly. No HMAC protection was found.", 23,
            reqId, PKIFailureInfo.badMessageCheck, PKIFailureInfo.incorrectData);
    log.trace("<test03CrmfHttpOkUser");
}

From source file:org.ejbca.core.protocol.cmp.CrmfRequestTest.java

License:Open Source License

@Test
public void test08SubjectDNSerialnumber() throws Exception {
    log.trace(">test08SubjectDNSerialnumber");
    // Create a new good USER
    String cmpsntestUsername = "cmpsntest";
    String cmpsntest2Username = "cmpsntest2";
    final X500Name userDN1 = createCmpUser(cmpsntestUsername, "C=SE,SN=12234567,CN=cmpsntest", true);

    try {/*from  w  w w . j ava2 s. c o m*/
        byte[] nonce = CmpMessageHelper.createSenderNonce();
        byte[] transid = CmpMessageHelper.createSenderNonce();

        PKIMessage req = genCertReq(ISSUER_DN, userDN1, this.keys, this.cacert, nonce, transid, false, null,
                null, null, null, null, null);
        assertNotNull(req);
        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        byte[] ba = bao.toByteArray();
        // Send request and receive response
        byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
        checkCmpResponseGeneral(resp, ISSUER_DN, userDN1, this.cacert, nonce, transid, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        X509Certificate cert = checkCmpCertRepMessage(userDN1, this.cacert, resp, reqId);

        // Now revoke the certificate!
        PKIMessage rev = genRevReq(ISSUER_DN, userDN1, cert.getSerialNumber(), this.cacert, nonce, transid,
                true, null, null);
        assertNotNull(rev);
        rev = protectPKIMessage(rev, false, "foo123", 567);
        assertNotNull(rev);
        ByteArrayOutputStream baorev = new ByteArrayOutputStream();
        DEROutputStream outrev = new DEROutputStream(baorev);
        outrev.writeObject(rev);
        byte[] barev = baorev.toByteArray();
        // Send request and receive response
        resp = sendCmpHttp(barev, 200, cmpAlias);
        checkCmpResponseGeneral(resp, ISSUER_DN, userDN1, this.cacert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        int revStatus = checkRevokeStatus(ISSUER_DN, CertTools.getSerialNumber(cert));
        assertNotEquals("Revocation request failed to revoke the certificate", RevokedCertInfo.NOT_REVOKED,
                revStatus);

        // Create another USER with the subjectDN serialnumber spelled "SERIALNUMBER" instead of "SN"
        KeyPair keys2 = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

        final X500Name userDN2 = createCmpUser(cmpsntest2Username, "C=SE,SERIALNUMBER=123456789,CN=cmpsntest2",
                true);
        req = genCertReq(ISSUER_DN, userDN2, keys2, this.cacert, nonce, transid, false, null, null, null, null,
                null, null);
        assertNotNull(req);
        ir = (CertReqMessages) req.getBody().getContent();
        reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        out.writeObject(req);
        ba = bao.toByteArray();
        // Send request and receive response
        resp = sendCmpHttp(ba, 200, cmpAlias);
        checkCmpResponseGeneral(resp, ISSUER_DN, userDN2, this.cacert, nonce, transid, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        cert = checkCmpCertRepMessage(userDN2, this.cacert, resp, reqId);

        // Now revoke this certificate too
        rev = genRevReq(ISSUER_DN, userDN2, cert.getSerialNumber(), this.cacert, nonce, transid, true, null,
                null);
        assertNotNull(rev);
        rev = protectPKIMessage(rev, false, "foo123", 567);
        assertNotNull(rev);
        baorev = new ByteArrayOutputStream();
        outrev = new DEROutputStream(baorev);
        outrev.writeObject(rev);
        barev = baorev.toByteArray();
        // Send request and receive response
        resp = sendCmpHttp(barev, 200, cmpAlias);
        checkCmpResponseGeneral(resp, ISSUER_DN, userDN2, this.cacert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        revStatus = checkRevokeStatus(ISSUER_DN, CertTools.getSerialNumber(cert));
        assertNotEquals("Revocation request failed to revoke the certificate", RevokedCertInfo.NOT_REVOKED,
                revStatus);

        log.trace("<test08SubjectDNSerialnumber");
    } finally {
        this.endEntityManagementSession.deleteUser(ADMIN, cmpsntestUsername);
        this.endEntityManagementSession.deleteUser(ADMIN, cmpsntest2Username);
    }
}

From source file:org.ejbca.core.protocol.cmp.CrmfRequestTest.java

License:Open Source License

@Test
public void test10EscapedCharsInDN() throws Exception {
    log.trace(">test10EscapedCharsInDN");

    this.cmpConfiguration.setExtractUsernameComponent(cmpAlias, "DN");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    // --------------- Send a CRMF request with the whole DN as username with escapable characters --------------- //
    final String sRequestName = "CN=another\0nullguy%00<do>";
    // Create a new good USER
    final X500Name requestName = createCmpUser(sRequestName, sRequestName, false);

    try {//from w ww .j a  v  a2s .com
        PKIMessage req = genCertReq(ISSUER_DN, requestName, this.keys, this.cacert, nonce, transid, false, null,
                null, null, null, null, null);
        assertNotNull(req);
        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        byte[] ba = bao.toByteArray();
        // Send request and receive response
        byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
        checkCmpResponseGeneral(resp, ISSUER_DN, requestName, this.cacert, nonce, transid, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        X509Certificate cert = checkCmpCertRepMessage(new X500Name(StringTools.strip(sRequestName)),
                this.cacert, resp, reqId);
        assertNotNull(cert);

        // Now revoke the bastard!
        PKIMessage rev = genRevReq(ISSUER_DN, requestName, cert.getSerialNumber(), this.cacert, nonce, transid,
                true, null, null);
        assertNotNull(rev);
        rev = protectPKIMessage(rev, false, "foo123", 567);
        ByteArrayOutputStream baorev = new ByteArrayOutputStream();
        DEROutputStream outrev = new DEROutputStream(baorev);
        outrev.writeObject(rev);
        byte[] barev = baorev.toByteArray();
        // Send request and receive response
        resp = sendCmpHttp(barev, 200, cmpAlias);
        checkCmpResponseGeneral(resp, ISSUER_DN, requestName, this.cacert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        int revStatus = checkRevokeStatus(ISSUER_DN, CertTools.getSerialNumber(cert));
        assertNotEquals("Revocation request failed to revoke the certificate", RevokedCertInfo.NOT_REVOKED,
                revStatus);
    } finally {
        String escapedName = StringTools.stripUsername(sRequestName);
        try {
            this.endEntityManagementSession.deleteUser(ADMIN, escapedName);
        } catch (NotFoundException e) {
            // A test probably failed before creating the entity
            log.debug("Failed to delete USER: " + escapedName);
        }
    }

    // --------------- Send a CRMF request with a username with escapable characters --------------- //
    final String username = "another\0nullguy%00";
    final String sDN = "CN=" + username + ", C=SE, O=hejsan";
    KeyPair key2 = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

    // Create a new good USER
    final X500Name dn = createCmpUser(username, sDN, false);

    try {

        PKIMessage req = genCertReq(ISSUER_DN, dn, key2, this.cacert, nonce, transid, false, null, null, null,
                null, null, null);
        assertNotNull(req);
        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        byte[] ba = bao.toByteArray();
        // Send request and receive response
        byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
        checkCmpResponseGeneral(resp, ISSUER_DN, dn, this.cacert, nonce, transid, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        X509Certificate cert = checkCmpCertRepMessage(dn, this.cacert, resp, reqId);
        assertNotNull(cert);

        // Now revoke the bastard!
        PKIMessage rev = genRevReq(ISSUER_DN, dn, cert.getSerialNumber(), this.cacert, nonce, transid, true,
                null, null);
        assertNotNull(rev);
        rev = protectPKIMessage(rev, false, "foo123", 567);
        ByteArrayOutputStream baorev = new ByteArrayOutputStream();
        DEROutputStream outrev = new DEROutputStream(baorev);
        outrev.writeObject(rev);
        byte[] barev = baorev.toByteArray();
        // Send request and receive response
        resp = sendCmpHttp(barev, 200, cmpAlias);
        checkCmpResponseGeneral(resp, ISSUER_DN, dn, this.cacert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        int revStatus = checkRevokeStatus(ISSUER_DN, CertTools.getSerialNumber(cert));
        assertNotEquals("Revocation request failed to revoke the certificate", RevokedCertInfo.NOT_REVOKED,
                revStatus);

    } finally {
        String escapedName = StringTools.strip(username);
        try {
            this.endEntityManagementSession.deleteUser(ADMIN, escapedName);
        } catch (NotFoundException e) {
            // A test probably failed before creating the entity
            log.debug("Failed to delete USER: " + escapedName);
        }
    }

    log.trace("<test10EscapedCharsInDN");
}

From source file:org.ejbca.core.protocol.cmp.CrmfRequestTest.java

License:Open Source License

@Test
public void test11IncludingCertChainInSignedCMPResponse() throws Exception {

    //---------- Create SubCA signed by testx509ca (rootCA) ------------- //
    String subcaDN = "CN=SubTestCA";
    int subcaID = subcaDN.hashCode();
    int cryptoTokenId = CryptoTokenTestUtils.createCryptoTokenForCA(ADMIN, null, true, false, subcaDN, "1024");
    final String username = "cmptest";
    try {/*from   w w w  .ja  v  a2 s . com*/
        final CAToken catoken = CaTestUtils.createCaToken(cryptoTokenId,
                AlgorithmConstants.SIGALG_SHA256_WITH_RSA, AlgorithmConstants.SIGALG_SHA256_WITH_RSA);
        final List<ExtendedCAServiceInfo> extendedCaServices = new ArrayList<ExtendedCAServiceInfo>(2);
        extendedCaServices.add(new KeyRecoveryCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE));
        String caname = CertTools.getPartFromDN(subcaDN, "CN");
        boolean ldapOrder = !CertTools.isDNReversed(subcaDN);
        X509CAInfo cainfo = new X509CAInfo(subcaDN, caname, CAConstants.CA_ACTIVE,
                CertificateProfileConstants.CERTPROFILE_FIXED_SUBCA, 3650, this.caid,
                this.testx509ca.getCertificateChain(), catoken);
        cainfo.setDescription("JUnit RSA SubCA");
        cainfo.setExtendedCAServiceInfos(extendedCaServices);
        cainfo.setUseLdapDnOrder(ldapOrder);
        cainfo.setCmpRaAuthSecret("foo123");

        CAAdminSessionRemote caAdminSession = EjbRemoteHelper.INSTANCE
                .getRemoteSession(CAAdminSessionRemote.class);
        caAdminSession.createCA(ADMIN, cainfo);
        assertTrue(this.caSession.existsCa(subcaID));
        cainfo = (X509CAInfo) this.caSession.getCAInfo(ADMIN, subcaID);
        X509Certificate subcaCert = (X509Certificate) cainfo.getCertificateChain().iterator().next();

        // --------- Create a user ----------------- //
        boolean userExists = false;
        final X500Name userDN = new X500Name("C=SE,O=PrimeKey,CN=cmptest");
        EndEntityInformation user = new EndEntityInformation("cmptest", userDN.toString(), subcaID, null,
                "cmptest@primekey.se", new EndEntityType(EndEntityTypes.ENDUSER),
                //                    SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, 
                this.eepDnOverrideId, this.cpDnOverrideId, SecConst.TOKEN_SOFT_PEM, 0, null);
        user.setPassword("foo123");
        try {
            this.endEntityManagementSession.addUser(ADMIN, user, true);
            log.debug("created user: cmptest, foo123, " + userDN);
        } catch (Exception e) {
            userExists = true;
        }

        if (userExists) {
            log.debug("User cmptest already exists.");
            this.endEntityManagementSession.changeUser(ADMIN, user, true);
            this.endEntityManagementSession.setUserStatus(ADMIN, "cmptest", EndEntityConstants.STATUS_NEW);
            log.debug("Reset status to NEW");
        }

        assertTrue(this.endEntityManagementSession.existsUser("cmptest"));
        EndEntityAccessSessionRemote eeAccessSession = EjbRemoteHelper.INSTANCE
                .getRemoteSession(EndEntityAccessSessionRemote.class);
        EndEntityInformation ee = eeAccessSession.findUser(ADMIN, "cmptest");
        assertEquals(subcaID, ee.getCAId());

        // -------- generate and send a CMP request -------------- //
        byte[] nonce = CmpMessageHelper.createSenderNonce();
        byte[] transid = CmpMessageHelper.createSenderNonce();

        PKIMessage req = genCertReq(subcaDN, userDN, this.keys, subcaCert, nonce, transid, false, null, null,
                null, null, null, null);
        assertNotNull(req);
        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        byte[] ba = bao.toByteArray();
        // Send request and receive response
        byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
        checkCmpResponseGeneral(resp, subcaDN, userDN, subcaCert, nonce, transid, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        final X509Certificate cert = checkCmpCertRepMessage(userDN, subcaCert, resp, reqId);
        assertNotNull(cert);

        // ------- Check that the entire certificate chain is in the extraCerts field in the response
        PKIMessage respMsg = null;
        ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
        try {
            respMsg = PKIMessage.getInstance(asn1InputStream.readObject());
        } finally {
            asn1InputStream.close();
        }
        assertNotNull(respMsg);

        CMPCertificate[] certChain = respMsg.getExtraCerts();
        assertEquals(2, certChain.length);
        assertEquals(subcaDN, certChain[0].getX509v3PKCert().getSubject().toString());
        assertEquals(ISSUER_DN, certChain[1].getX509v3PKCert().getSubject().toString());
    } finally {
        try {
            this.endEntityManagementSession.deleteUser(ADMIN, username);
        } catch (NotFoundException e) {
            // A test probably failed before creating the entity
            log.debug("Failed to delete user: " + username);
        }
        CryptoTokenTestUtils.removeCryptoToken(null, cryptoTokenId);
        // Remove CA certificate of CA that we will remove
        Collection<Certificate> certs = this.caSession.getCAInfo(ADMIN, subcaID).getCertificateChain();
        this.internalCertStoreSession.removeCertificate(certs.iterator().next());
        // Remove the CA itself
        this.caSession.removeCA(ADMIN, subcaID);
    }
}