Example usage for org.bouncycastle.asn1 ASN1InputStream readObject

List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject

Introduction

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

Prototype

public ASN1Primitive readObject() throws IOException 

Source Link

Usage

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

License:Open Source License

/**
 * Sends a KeyUpdateRequest concerning a revoked certificate. A CMP error message is expected and no certificate renewal.
 * //from   w w w . j  a  v  a  2  s  . c  o m
 * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal)
 * - Pre-configuration: Sets cmp.allowautomaticrenewal to 'true' and tests that the resetting of configuration has worked.
 * - Pre-configuration: Sets cmp.allowupdatewithsamekey to 'true'
 * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful.
 * - Revokes cert and tests that the revocation 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
 * - Sends the request using HTTP and receives a response.
 * - Examines the response:
 *      - Checks that the response is not empty or null
 *      - Checks that the protection algorithm is sha1WithRSAEncryption
 *      - Checks that the signer is the expected CA
 *      - Verifies the response's 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
 *      - Parses the response and checks that the parsing did not result in a 'null'
 *      - Checks that the CMP response message tag number is '23', indicating a CMP error message
 *      - Checks that the CMP response message contain the expected error details text
 * 
 * @throws Exception
 */
@Test
public void test03UpdateRevokedCert() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">test03UpdateRevokedCert");
    }

    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;
    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);

    this.certificateStoreSession.setRevokeStatus(ADMIN, certificate,
            RevokedCertInfo.REVOCATION_REASON_CESSATIONOFOPERATION, null);
    assertTrue("Failed to revoke the test certificate", this.certificateStoreSession
            .isRevoked(CertTools.getIssuerDN(certificate), CertTools.getSerialNumber(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);

    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 = "The certificate attached to the PKIMessage in the extraCert field is not active.";
    assertEquals(expectedErrMsg, errMsg);

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

}

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

License:Open Source License

/**
 * Sends a KeyUpdateRequest concerning a certificate that does not exist in the database. A CMP error message is expected and no certificate renewal.
 * //from  ww w . j ava  2s  . co  m
 * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal)
 * - Pre-configuration: Sets cmp.allowautomaticrenewal to 'true' and tests that the resetting of configuration has worked.
 * - Pre-configuration: Sets cmp.allowupdatewithsamekey to 'true'
 * - Generates a self-signed certificate, fakecert
 * - Generates a CMP KeyUpdate Request and tests that such request has been created.
 * - Signs the CMP request using fakecert and attaches fakecert to the CMP request. Tests that the CMP request is still not null
 * - 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
 *       - Checks 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
 *       - Parses the response and checks that the parsing did not result in a 'null'
 *       - Checks that the CMP response message tag number is '23', indicating a CMP error message
 *       - Checks that the CMP response message contain the expected error details text
 * 
 * @throws Exception
 */
@Test
public void test04UpdateKeyWithFakeCert() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">test04UpdateKeyWithFakeCert");
    }

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

    //--------------- create the user and issue his first certificate -----------------
    final String fakeUsername = "fakeuser";
    final X500Name fakeUserDN = new X500Name("CN=" + fakeUsername + ",C=SE");
    createUser(fakeUsername, fakeUserDN.toString(), "foo123");

    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    Certificate fakeCert = CertTools.genSelfCert(fakeUserDN.toString(), 30, null, keys.getPrivate(),
            keys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false);
    assertNotNull("Failed to create a test certificate", fakeCert);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);

    // Sending a request with a certificate that neither it nor the issuer CA is in the database
    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);

    CMPCertificate[] extraCert = getCMPCert(fakeCert);
    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);

    PKIBody body = respObject.getBody();
    assertEquals(23, body.getType());
    ErrorMsgContent err = (ErrorMsgContent) body.getContent();
    String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    String expectedErrMsg = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database.";
    assertEquals(expectedErrMsg, errMsg);

    // sending another renewal request with a certificate issued by an existing CA but the certificate itself is not in the database        
    // A certificate, not in the database, issued by TestCA
    byte[] fakecertBytes = Base64.decode(("MIIB6TCCAVKgAwIBAgIIIKF3bEBbbyQwDQYJKoZIhvcNAQELBQAwETEPMA0GA1UE"
            + "AwwGVGVzdENBMB4XDTEzMDMxMjExMTcyMVoXDTEzMDMyMjExMjcyMFowIDERMA8G"
            + "A1UEAwwIZmFrZXVzZXIxCzAJBgNVBAYTAlNFMFwwDQYJKoZIhvcNAQEBBQADSwAw"
            + "SAJBAKZlXrI3TwziiDK9/E1V4n6PCXhpRERSLWPEpRvRPWfpvazpq7R2UZZRq5i2"
            + "hrqKDbfLdAouh2J7AIlUZG3cdJECAwEAAaN/MH0wHQYDVR0OBBYEFCb2tsZTXOh7"
            + "FjjVXpSxkJ79P3tJMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAURmtK3gFt81Bp"
            + "3z+YZuzBm65Ja6IwDgYDVR0PAQH/BAQDAgXgMB0GA1UdJQQWMBQGCCsGAQUFBwMC"
            + "BggrBgEFBQcDBDANBgkqhkiG9w0BAQsFAAOBgQAmclw6cwuQkiPSN4bHOP5S7bdU"
            + "+UKXLIkk1L84q0WQfblNzYkcDXMsxwJ1dv2Yd/dxIjtVjrhVIUrRMA70jtWs31CH"
            + "t9ofdgncIdtzZo49mLRQDwhTCApoLf0BCNb2rWpzCPWQTa97y0u5T65m7DAkBTV/" + "JAkFQIZCLSAci++qPA==")
                    .getBytes());
    fakeCert = CertTools.getCertfromByteArray(fakecertBytes);

    req = genRenewalReq(fakeUserDN, this.cacert, this.nonce, this.transid, keys, false, null, null, pAlg,
            new DEROctetString(this.nonce));
    assertNotNull("Failed to generate a CMP renewal request", req);

    extraCert = getCMPCert(fakeCert);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);

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

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

    body = respObject.getBody();
    assertEquals(23, body.getType());
    err = (ErrorMsgContent) body.getContent();
    errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    expectedErrMsg = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database.";
    assertEquals(expectedErrMsg, errMsg);

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

}

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

License:Open Source License

/**
 * Sends a KeyUpdateRequest using the same old keys and the configurations is NOT to allow the use of the same key. 
 * A CMP error message is expected and no certificate renewal.
 * /*from  w  w  w .j  ava  2  s  .c o  m*/
 * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal)
 * - Pre-configuration: Sets cmp.allowautomaticrenewal to 'true' and tests that the resetting of configuration has worked.
 * - Pre-configuration: Sets cmp.allowupdatewithsamekey to 'false'
 * - 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
 * - Sends the request using HTTP and receives a response.
 * - Examines the response:
 *       - Checks that the response is not empty or null
 *       - Checks that the protection algorithm is sha1WithRSAEncryption
 *       - Checks 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
 *       - Parses the response and checks that the parsing did not result in a 'null'
 *       - Checks that the CMP response message tag number is '23', indicating a CMP error message
 *       - Checks that the CMP response message contain the expected error details text
 * 
 * @throws Exception
 */
@Test
public void test05UpdateWithSameKeyNotAllowed() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">test07UpdateWithSameKeyNotAllowed");
    }

    this.cmpConfiguration.setRAMode(this.cmpAlias, false);
    this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true);
    this.cmpConfiguration.setKurAllowSameKey(this.cmpAlias, false);
    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;
    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(this.nonce));
    assertNotNull("Failed to generate a CMP renewal request", req);

    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 = "Invalid key. The public key in the KeyUpdateRequest is the same as the public key in the existing end entity certificate";
    assertEquals(expectedErrMsg, errMsg);

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

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

License:Open Source License

/**
 * Sends a KeyUpdateRequest in RA mode and the request sender is not an authorized administrator. 
 * A CMP error message is expected and no certificate renewal.
 * //  w  ww. ja v  a 2  s . com
 * - 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 test08RAModeNonAdmin() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace("test10RAModeNonAdmin()");
    }

    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, this.userDN,
            this.issuerDN, pAlg, new DEROctetString("CMPTESTPROFILE".getBytes()));
    assertNotNull("Failed to generate a CMP renewal request", req);

    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 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 = "'" + this.userDN + "' is not an authorized administrator.";
    assertEquals(expectedErrMsg, errMsg);

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

}

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.
 * //from   w  ww .  ja  v a2s . co m
 * - 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 the authentication module is NOT set to 'EndEntityCertificate'. 
 * A CMP error message is expected and no certificate renewal.
 * //from   www .  j  a v  a 2  s.c o  m
 * - Pre-configuration: Sets the operational mode to RA mode (cmp.raoperationalmode=ra)
 * - Pre-configuration: Sets the cmp.authenticationmodule to 'DnPartPwd'
 * - Pre-configuration: Sets the cmp.authenticationparameters to 'OU'
 * - 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 test12ECCNotSetInRA() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace("test12ECCNotSetInRA()");
    }

    this.cmpConfiguration.setRAMode(this.cmpAlias, true);
    this.cmpConfiguration.setAuthenticationModule(this.cmpAlias, CmpConfiguration.AUTHMODULE_DN_PART_PWD);
    this.cmpConfiguration.setAuthenticationParameters(this.cmpAlias, "OU");
    this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true);
    this.cmpConfiguration.setKurAllowSameKey(this.cmpAlias, true);
    this.cmpConfiguration.setCMPDefaultCA(this.cmpAlias, "");
    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,
            null, pAlg, null);
    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");
    final 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 = "EndEnityCertificate authentication module is not configured. For a KeyUpdate request to be authentication "
            + "in RA mode, EndEntityCertificate authentication module has to be set and configured";
    assertEquals(expectedErrMsg, errMsg);

    removeAuthenticationToken(admToken, admCert, "cmpTestAdmin");

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

}

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.
 * /*w w  w .j  av  a  2  s. c  o m*/
 * - 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. j  av  a 2 s  .  c o  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

private static X509Certificate checkKurCertRepMessage(X500Name eeDN, Certificate issuerCert, byte[] retMsg,
        int requestId) throws Exception {
    ////from  www.  ja v  a2 s  .c o m
    // Parse response message
    //

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

    assertNotNull(respObject);

    // Verify body type
    PKIBody body = respObject.getBody();
    int tag = body.getType();
    assertEquals(8, tag);

    // Verify the response
    CertRepMessage c = (CertRepMessage) body.getContent();
    assertNotNull(c);
    CertResponse resp = c.getResponse()[0];
    assertNotNull(resp);
    assertEquals(resp.getCertReqId().getValue().intValue(), requestId);

    // Verify response status
    PKIStatusInfo info = resp.getStatus();
    assertNotNull(info);
    assertEquals(0, info.getStatus().intValue());

    // Verify response certificate
    CertifiedKeyPair kp = resp.getCertifiedKeyPair();
    assertNotNull(kp);
    CertOrEncCert cc = kp.getCertOrEncCert();
    assertNotNull(cc);
    final CMPCertificate cmpcert = cc.getCertificate();
    assertNotNull(cmpcert);
    X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(cmpcert.getEncoded());
    final X500Name name = new X500Name(CertTools.getSubjectDN(cert));
    assertArrayEquals(eeDN.getEncoded(), name.getEncoded());
    assertEquals(CertTools.stringToBCDNString(CertTools.getIssuerDN(cert)), CertTools.getSubjectDN(issuerCert));

    // Verify the issuer of cert
    CMPCertificate respCmpCaCert = c.getCaPubs()[0];
    final X509Certificate respCaCert = (X509Certificate) CertTools
            .getCertfromByteArray(respCmpCaCert.getEncoded());
    assertEquals(CertTools.getFingerprintAsString(issuerCert), CertTools.getFingerprintAsString(respCaCert));

    Collection<Certificate> cacerts = new ArrayList<Certificate>();
    cacerts.add(issuerCert);
    assertTrue(CertTools.verify(cert, cacerts));
    cacerts = new ArrayList<Certificate>();
    cacerts.add(respCaCert);
    assertTrue(CertTools.verify(cert, cacerts));
    return cert;
}

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

License:Open Source License

@Test
public void test03BlueXCrmf() throws Exception {
    PKIMessage req = null;/*from w w  w. jav  a 2s  .  c  o m*/
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(bluexir));
    try {
        req = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    byte[] resp = sendCmpTcp(bluexir, 5);
    assertNotNull(resp);
    byte[] senderNonce = req.getHeader().getSenderNonce().getOctets();
    byte[] transId = req.getHeader().getTransactionID().getOctets();
    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    checkCmpResponseGeneral(resp, issuerDN, userDN, this.cacert, senderNonce, transId, true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
}