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.cmp.CrmfKeyUpdateTest.java

License:Open Source License

/**
 * Sends a KeyUpdateRequest in RA mode without filling the 'issuerDN' field in the request. 
 * Successful operation is expected and a new certificate is received.
 * /*from w  ww  .  ja v  a 2s. co m*/
 * - Pre-configuration: Sets the operational mode to RA mode (cmp.raoperationalmode=ra)
 * - Pre-configuration: Sets the cmp.authenticationmodule to 'EndEntityCertificate'
 * - Pre-configuration: Sets the cmp.authenticationparameters to 'TestCA'
 * - Pre-configuration: Set cmp.checkadminauthorization to 'true'
 * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful.
 * - Generates a CMP KeyUpdate Request and tests that such request has been created.
 * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null
 * - Verifies the signature of the CMP request
 * - Sends the request using HTTP and receives an response.
 * - Examines the response:
 *      - Checks that the response is not empty or null
 *      - Checks that the protection algorithm is sha1WithRSAEncryption
 *      - Check that the signer is the expected CA
 *      - Verifies the response signature
 *      - Checks that the response's senderNonce is 16 bytes long
 *      - Checks that the request's senderNonce is the same as the response's recipientNonce
 *      - Checks that the request and the response has the same transactionID
 *      - Obtains the certificate from the response
 *      - Checks that the obtained certificate has the right subjectDN and issuerDN
 * 
 * @throws Exception
 */
@Test
public void test09RANoIssuer() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace("test11RANoIssuer()");
    }

    this.cmpConfiguration.setRAMode(this.cmpAlias, true);
    this.cmpConfiguration.setAuthenticationModule(this.cmpAlias,
            CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(this.cmpAlias, "TestCA");
    this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //------------------ create the user and issue his first certificate -------------
    createUser(this.username, this.userDN.toString(), "foo123");
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    Certificate certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123",
            new PublicKeyWrapper(keys.getPublic()));
    assertNotNull("Failed to create a test certificate", certificate);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, this.userDN,
            null, pAlg, new DEROctetString("CMPTESTPROFILE".getBytes()));
    assertNotNull("Failed to generate a CMP renewal request", req);
    CertReqMessages kur = (CertReqMessages) req.getBody().getContent();
    int reqId = kur.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();

    createUser("cmpTestAdmin", "CN=cmpTestAdmin,C=SE", "foo123");
    KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
    AuthenticationToken admToken = createAdminToken(admkeys, "cmpTestAdmin", "CN=cmpTestAdmin,C=SE");
    Certificate admCert = getCertFromCredentials(admToken);
    CMPCertificate[] extraCert = getCMPCert(admCert);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    //send request and recieve response
    byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkKurCertRepMessage(this.userDN, this.cacert, resp, reqId);
    assertNotNull("Failed to renew the certificate", cert);

    removeAuthenticationToken(admToken, admCert, "cmpTestAdmin");

    if (log.isTraceEnabled()) {
        log.trace("<test11RANoIssuer()");
    }

}

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

License:Open Source License

/**
 * Sends a KeyUpdateRequest in RA mode with neither subjectDN nor issuerDN are set in the request. 
 * A CMP error message is expected and no certificate renewal.
 * /* www  .j  a  va2 s  .c om*/
 * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal)
 * - Pre-configuration: Sets the cmp.authenticationmodule to 'EndEntityCertificate'
 * - Pre-configuration: Sets the cmp.authenticationparameters to 'TestCA'
 * - Pre-configuration: Set cmp.checkadminauthorization to 'true'
 * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful.
 * - Generates a CMP KeyUpdate Request and tests that such request has been created.
 * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null
 * - Verifies the signature of the CMP request
 * - Sends the request using HTTP and receives an response.
 * - Examines the response:
 *      - Checks that the response is not empty or null
 *      - Checks that the protection algorithm is sha1WithRSAEncryption
 *      - Check that the signer is the expected CA
 *      - Verifies the response signature
 *      - Checks that the response's senderNonce is 16 bytes long
 *      - Checks that the request's senderNonce is the same as the response's recipientNonce
 *      - Checks that the request and the response has the same transactionID
 *      - Parse the response and make sure that the parsing did not result in a 'null'
 *      - Check that the CMP response message tag number is '23', indicating a CMP error message
 *      - Check that the CMP response message contain the expected error details text
 * 
 * @throws Exception
 */
@Test
public void test10RANoIssuerNoSubjectDN() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace("test12RANoIssuerNoSubjetDN()");
    }

    this.cmpConfiguration.setRAMode(this.cmpAlias, true);
    this.cmpConfiguration.setAuthenticationModule(this.cmpAlias,
            CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(this.cmpAlias, "TestCA");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //------------------ create the user and issue his first certificate -------------
    createUser(this.username, this.userDN.toString(), "foo123");
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    Certificate certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123",
            new PublicKeyWrapper(keys.getPublic()));
    assertNotNull("Failed to create a test certificate", certificate);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, null, null,
            pAlg, new DEROctetString("CMPTESTPROFILE".getBytes()));
    assertNotNull("Failed to generate a CMP renewal request", req);

    createUser("cmpTestAdmin", "CN=cmpTestAdmin,C=SE", "foo123");
    KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
    AuthenticationToken admToken = createAdminToken(admkeys, "cmpTestAdmin", "CN=cmpTestAdmin,C=SE");
    Certificate admCert = getCertFromCredentials(admToken);
    CMPCertificate[] extraCert = getCMPCert(admCert);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    //send request and recieve response
    byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    final PKIBody body = respObject.getBody();
    assertEquals(23, body.getType());
    ErrorMsgContent err = (ErrorMsgContent) body.getContent();
    final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    final String expectedErrMsg = "Cannot find a SubjectDN in the request";
    assertEquals(expectedErrMsg, errMsg);

    removeAuthenticationToken(admToken, admCert, "cmpTestAdmin");

    if (log.isTraceEnabled()) {
        log.trace("<test12RANoIssuerNoSubjectDN()");
    }

}

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

License:Open Source License

/**
 * Sends a KeyUpdateRequest in RA mode when there are more than one authentication module configured. 
 * Successful operation is expected and a new certificate is received.
 * //w  ww .j  a v  a  2s .c  o  m
 * - Pre-configuration: Sets the operational mode to RA mode (cmp.raoperationalmode=ra)
 * - Pre-configuration: Sets the cmp.authenticationmodule to "HMAC;DnPartPwd;EndEntityCertificate"
 * - Pre-configuration: Sets the cmp.authenticationparameters to "-;OU;TestCA"
 * - Pre-configuration: Set cmp.checkadminauthorization to 'true'
 * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful.
 * - Generates a CMP KeyUpdate Request and tests that such request has been created.
 * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null
 * - Verifies the signature of the CMP request
 * - Sends the request using HTTP and receives an response.
 * - Examines the response:
 *      - Checks that the response is not empty or null
 *      - Checks that the protection algorithm is sha1WithRSAEncryption
 *      - Check that the signer is the expected CA
 *      - Verifies the response signature
 *      - Checks that the response's senderNonce is 16 bytes long
 *      - Checks that the request's senderNonce is the same as the response's recipientNonce
 *      - Checks that the request and the response has the same transactionID
 *      - Obtains the certificate from the response
 *      - Checks that the obtained certificate has the right subjectDN and issuerDN
 * 
 * @throws Exception
 */
@Test
public void test11RAMultipleAuthenticationModules() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace("test13RAMultipleAuthenticationModules");
    }

    this.cmpConfiguration.setRAMode(this.cmpAlias, true);
    String authmodules = CmpConfiguration.AUTHMODULE_HMAC + ";" + CmpConfiguration.AUTHMODULE_DN_PART_PWD + ";"
            + CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE;
    this.cmpConfiguration.setAuthenticationModule(this.cmpAlias, authmodules);
    this.cmpConfiguration.setAuthenticationParameters(this.cmpAlias, "-;OU;TestCA");
    this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //------------------ create the user and issue his first certificate -------------
    createUser(this.username, this.userDN.toString(), "foo123");
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    Certificate certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123",
            new PublicKeyWrapper(keys.getPublic()));
    assertNotNull("Failed to create a test certificate", certificate);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, this.userDN,
            null, pAlg, new DEROctetString("CMPTESTPROFILE".getBytes()));
    assertNotNull("Failed to generate a CMP renewal request", req);
    CertReqMessages kur = (CertReqMessages) req.getBody().getContent();
    int reqId = kur.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();

    createUser("cmpTestAdmin", "CN=cmpTestAdmin,C=SE", "foo123");
    KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
    AuthenticationToken admToken = createAdminToken(admkeys, "cmpTestAdmin", "CN=cmpTestAdmin,C=SE");
    Certificate admCert = getCertFromCredentials(admToken);
    CMPCertificate[] extraCert = getCMPCert(admCert);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    //send request and recieve response
    byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkKurCertRepMessage(this.userDN, this.cacert, resp, reqId);
    assertNotNull("Failed to renew the certificate", cert);

    removeAuthenticationToken(admToken, admCert, "cmpTestAdmin");

    if (log.isTraceEnabled()) {
        log.trace("<test13RAMultipleAuthenticationModules()");
    }

}

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

License:Open Source License

/**
 * Sends a KeyUpdateRequest by an admin concerning a certificate of another EndEntity in client mode. 
 * If the CA enforces unique public key, a CMP error message is expected and no certificate renewal.
 * If the CA does not enforce unique public key, a certificate will be renewed, though not the expected EndEntity certificate, but the admin certificate is renewed.
 * //from   w w w. j  a  v a2  s  .  c om
 * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal)
 * - Pre-configuration: Sets the cmp.authenticationmodule to 'EndEntityCertificate'
 * - Pre-configuration: Sets the cmp.authenticationparameters to 'TestCA'
 * - Pre-configuration: Sets the cmp.allowautomatickeyupdate to 'true'
 * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful.
 * - Generates a CMP KeyUpdate Request and tests that such request has been created.
 * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null
 * - Verifies the signature of the CMP request
 * - Sends the request using HTTP and receives an response.
 * - Examines the response:
 *      - Checks that the response is not empty or null
 *      - Checks that the protection algorithm is sha1WithRSAEncryption
 *      - Check that the signer is the expected CA
 *      - Verifies the response signature
 *      - Checks that the response's senderNonce is 16 bytes long
 *      - Checks that the request's senderNonce is the same as the response's recipientNonce
 *      - Checks that the request and the response has the same transactionID
 *      - Obtains the certificate from the response
 *      - Checks that the obtained certificate has the right subjectDN and issuerDN
 * 
 * @throws Exception
 */
@Test
public void test13AdminInClientMode() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace("test09RAMode()");
    }

    this.cmpConfiguration.setRAMode(this.cmpAlias, false);
    this.cmpConfiguration.setAuthenticationModule(this.cmpAlias,
            CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(this.cmpAlias, "TestCA");
    this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //------------------ create the user and issue his first certificate -------------
    createUser(this.username, this.userDN.toString(), "foo123");
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final Certificate certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123",
            new PublicKeyWrapper(keys.getPublic()));
    assertNotNull("Failed to create a test certificate", certificate);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, this.userDN,
            this.issuerDN, pAlg, new DEROctetString("CMPTESTPROFILE".getBytes()));
    assertNotNull("Failed to generate a CMP renewal request", req);
    //int reqId = req.getBody().getKur().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue();

    createUser("cmpTestAdmin", "CN=cmpTestAdmin,C=SE", "foo123");
    KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
    AuthenticationToken admToken = createAdminToken(admkeys, "cmpTestAdmin", "CN=cmpTestAdmin,C=SE");
    Certificate admCert = getCertFromCredentials(admToken);
    CMPCertificate[] extraCert = getCMPCert(admCert);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    //send request and recieve response
    byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    CAInfo cainfo = this.caSession.getCAInfo(ADMIN, this.caid);
    if (cainfo.isDoEnforceUniquePublicKeys()) {
        final PKIBody body = respObject.getBody();
        assertEquals(23, body.getType());
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        final String expectedErrMsg = "User 'cmpTestAdmin' is not allowed to use same key as another user is using.";
        assertEquals(expectedErrMsg, errMsg);
    } else {
        PKIBody body = respObject.getBody();
        int tag = body.getType();
        assertEquals(8, tag);
        CertRepMessage c = (CertRepMessage) body.getContent();
        assertNotNull(c);
        CMPCertificate cmpcert = c.getResponse()[0].getCertifiedKeyPair().getCertOrEncCert().getCertificate();
        assertNotNull(cmpcert);
        X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(cmpcert.getEncoded());
        assertNotNull("Failed to renew the certificate", cert);
        assertEquals("CN=cmpTestAdmin, C=SE", cert.getSubjectX500Principal().toString());
    }

    removeAuthenticationToken(admToken, admCert, "cmpTestAdmin");

    if (log.isTraceEnabled()) {
        log.trace("<test09RAMode()");
    }
}

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

License:Open Source License

/**
 * Sends a KeyUpdateRequest by an EndEntity concerning its own certificate in RA mode. 
 * A CMP error message is expected and no certificate renewal.
 * //from w  w w  .jav a 2  s.  co m
 * @throws Exception
 */
@Test
public void test14EndEntityRequestingInRAMode() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">test14KeyUpdateRequestOK");
    }

    this.cmpConfiguration.setRAMode(this.cmpAlias, true);
    this.cmpConfiguration.setAuthenticationModule(this.cmpAlias,
            CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(this.cmpAlias, "TestCA");
    this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true);
    this.cmpConfiguration.setKurAllowSameKey(this.cmpAlias, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //--------------- create the user and issue his first certificate -----------------
    createUser(this.username, this.userDN.toString(), "foo123");
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final Certificate certificate;
    try {
        certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123",
                new PublicKeyWrapper(keys.getPublic()));
    } catch (ObjectNotFoundException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (CADoesntExistsException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (EjbcaException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (AuthorizationDeniedException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (CesecoreException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    }
    assertNotNull("Failed to create a test certificate", certificate);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, null, null,
            pAlg, new DEROctetString(this.nonce));
    assertNotNull("Failed to generate a CMP renewal request", req);
    //int reqId = req.getBody().getKur().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue();

    CMPCertificate[] extraCert = getCMPCert(certificate);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);

    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, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    final PKIBody body = respObject.getBody();
    assertEquals(23, body.getType());
    ErrorMsgContent err = (ErrorMsgContent) body.getContent();
    final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();

    final String expectedErrMsg = "'CN=certRenewalUser,O=PrimeKey Solutions AB,C=SE' is not an authorized administrator.";
    assertEquals(expectedErrMsg, errMsg);

    if (log.isTraceEnabled()) {
        log.trace("<test14KeyUpdateRequestOK");
    }
}

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

License:Open Source License

/**
 * Tests the possibility to use different signature algorithms in CMP requests and responses.
 * //ww w. j a v  a  2  s.co m
 * A KeyUpdate request, signed using ECDSA with SHA256, is sent to a CA that uses RSA with SHA256 as signature algorithm.
 * The expected response is signed by RSA with SHA256.
 * 
 * @throws Exception
 */
@Test
public void test15KeyUpdateMixAlgorithms() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">test15KeyUpdateMixAlgorithms");
    }

    this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true);
    this.cmpConfiguration.setKurAllowSameKey(this.cmpAlias, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //--------------- create the user and issue his first certificate -----------------
    createUser(this.username, this.userDN.toString(), "foo123");
    KeyPair keys = KeyTools.genKeys("prime192v1", AlgorithmConstants.KEYALGORITHM_ECDSA);
    final Certificate certificate;
    try {
        certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123",
                new PublicKeyWrapper(keys.getPublic()));
    } catch (ObjectNotFoundException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (CADoesntExistsException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (EjbcaException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (AuthorizationDeniedException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (CesecoreException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    }
    assertNotNull("Failed to create a test certificate", certificate);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(X9ObjectIdentifiers.ecdsa_with_SHA256);
    PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, null, null,
            pAlg, new DEROctetString(this.nonce));
    assertNotNull("Failed to generate a CMP renewal request", req);
    CertReqMessages kur = (CertReqMessages) req.getBody().getContent();
    int reqId = kur.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    CMPCertificate[] extraCert = getCMPCert(certificate);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(),
            CMSSignedGenerator.DIGEST_SHA256, "BC");
    assertNotNull(req);

    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, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, true, null,
            PKCSObjectIdentifiers.sha256WithRSAEncryption.getId());
    X509Certificate cert = checkKurCertRepMessage(this.userDN, this.cacert, resp, reqId);
    assertNotNull("Failed to renew the certificate", cert);
    assertTrue("The new certificate's keys are incorrect.", cert.getPublicKey().equals(keys.getPublic()));

    if (log.isTraceEnabled()) {
        log.trace("<test15KeyUpdateMixAlgorithms");
    }

}

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

License:Open Source License

private PKIMessage createPKIMessage(final String issuerDN, final String subjectDN)
        throws InvalidAlgorithmParameterException, IOException {
    KeyPair keys = KeyTools.genKeys("1024", "RSA");
    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setValidity(myOptionalValidity);
    myCertTemplate.setIssuer(new X500Name(issuerDN));
    myCertTemplate.setSubject(new X500Name(subjectDN));
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {/* w ww . j  a  va  2 s.  c  o  m*/
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
    } finally {
        dIn.close();
    }
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    int bcku = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment | X509KeyUsage.nonRepudiation;
    X509KeyUsage ku = new X509KeyUsage(bcku);
    bOut = new ByteArrayOutputStream();
    dOut = new DEROutputStream(bOut);
    dOut.writeObject(ku);
    byte[] value = bOut.toByteArray();
    extgen.addExtension(Extension.keyUsage, false, new DEROctetString(value));
    myCertTemplate.setExtensions(extgen.generate());

    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);

    ProofOfPossession myProofOfPossession = new ProofOfPossession();
    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String("foo123"));
    AttributeTypeAndValue[] avs = { av };
    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);
    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(new X500Name("CN=bogusSubject")),
            new GeneralName(new X500Name("CN=bogusIssuer")));
    myPKIHeader.setMessageTime(new DERGeneralizedTime(new Date()));
    myPKIHeader.setSenderNonce(new DEROctetString(CmpMessageHelper.createSenderNonce()));
    myPKIHeader.setTransactionID(new DEROctetString(CmpMessageHelper.createSenderNonce()));

    PKIBody myPKIBody = new PKIBody(0, myCertReqMessages);
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}

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

License:Open Source License

@Test
public void test09KeyIdTest() {
    log.trace(">test09KeyIdTest()");

    DEROctetString octs = new DEROctetString("foo123".getBytes());
    String keyid = CmpMessageHelper.getStringFromOctets(octs);
    assertEquals("foo123", keyid);

    PKIHeaderBuilder headerbuilder = new PKIHeaderBuilder(2, new GeneralName(new X500Name("CN=Sender")),
            new GeneralName(new X500Name("CN=Recipient")));
    headerbuilder.setSenderKID(new DEROctetString("foo123".getBytes()));
    PKIHeader header = headerbuilder.build();
    keyid = CmpMessageHelper.getStringFromOctets(header.getSenderKID());
    assertEquals("foo123", keyid);

    log.trace("<test09KeyIdTest()");
}

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

License:Open Source License

/**
 * 1- Sends a CRMF request signed by RA1Admin to RA1. Expected: Success
 * 2- Sends a CRMF request signed by RA2Admin to RA2. Expected: Success
 * /*from   w  ww  . ja  va2s  . com*/
 * @throws Exception
 */
@Test
public void test01RA1SuccessfullCRMF() throws Exception {

    // Send CRMF message signed by RA1Admin to RA1
    String testUsername = "ra1testuser";
    String fingerprintCert = null;
    try {

        final X500Name testUserDN = new X500Name("CN=" + testUsername);
        KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        PKIMessage msg = genCertReq(ca1.getSubjectDN(), testUserDN, keys, ca1.getCACertificate(), nonce,
                transid, false, null, null, null, null, pAlg, new DEROctetString(nonce));
        assertNotNull("Generating CrmfRequest failed.", msg);

        CMPCertificate[] extraCert = getCMPCert(ra1admincert);
        msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra1adminkeys.getPrivate(),
                pAlg.getAlgorithm().getId(), "BC");
        assertNotNull("Signing CMP message failed", msg);
        //******************************************''''''
        final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(),
                "BC");
        sig.initVerify(ra1admincert.getPublicKey());
        sig.update(CmpMessageHelper.getProtectedBytes(msg));
        boolean verified = sig.verify(msg.getProtection().getBytes());
        assertTrue("Signing the message failed.", verified);
        //***************************************************

        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(msg);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, RA1_ALIAS);
        checkCmpResponseGeneral(resp, ca1.getSubjectDN(), testUserDN, ca1.getCACertificate(),
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        CertReqMessages ir = (CertReqMessages) msg.getBody().getContent();
        Certificate cert = checkCmpCertRepMessage(testUserDN, (X509Certificate) ca1.getCACertificate(), resp,
                ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
        assertNotNull("CrmfRequest did not return a certificate", cert);
        fingerprintCert = CertTools.getFingerprintAsString(cert);
    } finally {
        internalCertStoreSession.removeCertificate(fingerprintCert);
        endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused);
    }

    // Send CRMF message signed by RA2Admin to RA2
    testUsername = "ra2testuser";
    try {

        final X500Name testUserDN = new X500Name("CN=" + testUsername);
        KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        PKIMessage msg = genCertReq(ca2.getSubjectDN(), testUserDN, keys, ca2.getCACertificate(), nonce,
                transid, false, null, null, null, null, pAlg, new DEROctetString(nonce));
        assertNotNull("Generating CrmfRequest failed.", msg);

        CMPCertificate[] extraCert = getCMPCert(ra2admincert);
        msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra2adminkeys.getPrivate(),
                pAlg.getAlgorithm().getId(), "BC");
        assertNotNull("Signing CMP message failed.", msg);
        //******************************************''''''
        final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(),
                "BC");
        sig.initVerify(ra2admincert.getPublicKey());
        sig.update(CmpMessageHelper.getProtectedBytes(msg));
        boolean verified = sig.verify(msg.getProtection().getBytes());
        assertTrue("Signing the message failed.", verified);
        //***************************************************

        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(msg);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, RA2_ALIAS);
        checkCmpResponseGeneral(resp, ca2.getSubjectDN(), testUserDN, ca2.getCACertificate(),
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        CertReqMessages ir = (CertReqMessages) msg.getBody().getContent();
        Certificate cert = checkCmpCertRepMessage(testUserDN, (X509Certificate) ca2.getCACertificate(), resp,
                ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
        assertNotNull("CrmfRequest did not return a certificate", cert);
        fingerprintCert = CertTools.getFingerprintAsString(cert);
    } finally {
        internalCertStoreSession.removeCertificate(fingerprintCert);
        endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused);
    }

}

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

License:Open Source License

/**
 * 1- Sends a CRMF request signed by RA2Admin to RA1. Expected: Fail
 * 2- Sends a CRMF request signed by RA1Admin to RA2. Expected: Fail
 * //  w w  w.j a v a2 s  .  co m
 * @throws Exception
 */
@Test
public void test01RA1FailedCRMF() throws Exception {

    // Send CRMF message signed by RA2Admin to RA1
    String testUsername = "ra1testuser";
    X500Name testUserDN = new X500Name("CN=" + testUsername);
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage msg = genCertReq(ca1.getSubjectDN(), testUserDN, keys, ca1.getCACertificate(), nonce, transid,
            false, null, null, null, null, pAlg, new DEROctetString(nonce));
    assertNotNull("Generating CrmfRequest failed.", msg);

    CMPCertificate[] extraCert = getCMPCert(ra2admincert);
    msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra2adminkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull("Signing CMP message failed.", msg);
    //******************************************''''''
    Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC");
    sig.initVerify(ra2admincert.getPublicKey());
    sig.update(CmpMessageHelper.getProtectedBytes(msg));
    boolean verified = sig.verify(msg.getProtection().getBytes());
    assertTrue("Signing the message failed.", verified);
    //***************************************************

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(msg);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, RA1_ALIAS);
    checkCmpResponseGeneral(resp, ca1.getSubjectDN(), testUserDN, ca1.getCACertificate(),
            msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false,
            null, null);
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    PKIMessage respObject = null;
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull("Reading CMP response failed.", respObject);
    PKIBody body = respObject.getBody();
    assertEquals(PKIBody.TYPE_ERROR, body.getType());
    ErrorMsgContent err = (ErrorMsgContent) body.getContent();
    String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    String expectedErrMsg = "'CN=" + RA2_ADMIN + "' is not an authorized administrator.";
    assertEquals(expectedErrMsg, errMsg);

    // Send CRMF message signed by RA1Admin to RA2
    testUsername = "ra2testuser";
    testUserDN = new X500Name("CN=" + testUsername);
    keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    msg = genCertReq(ca2.getSubjectDN(), testUserDN, keys, ca2.getCACertificate(), nonce, transid, false, null,
            null, null, null, pAlg, new DEROctetString(nonce));
    assertNotNull("Generating CrmfRequest failed.", msg);

    extraCert = getCMPCert(ra1admincert);
    msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra1adminkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull("Signing CMP message failed.", msg);
    //******************************************''''''
    sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC");
    sig.initVerify(ra1admincert.getPublicKey());
    sig.update(CmpMessageHelper.getProtectedBytes(msg));
    verified = sig.verify(msg.getProtection().getBytes());
    assertTrue("Signing the message failed.", verified);
    //***************************************************

    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(msg);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, RA2_ALIAS);
    checkCmpResponseGeneral(resp, ca2.getSubjectDN(), testUserDN, ca2.getCACertificate(),
            msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false,
            null, null);
    asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull("Reading CMP response failed.", respObject);
    body = respObject.getBody();
    assertEquals(PKIBody.TYPE_ERROR, body.getType());
    err = (ErrorMsgContent) body.getContent();
    errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    expectedErrMsg = "'CN=" + RA1_ADMIN + "' is not an authorized administrator.";
    assertEquals(expectedErrMsg, errMsg);

}