Example usage for java.security KeyPair getPrivate

List of usage examples for java.security KeyPair getPrivate

Introduction

In this page you can find the example usage for java.security KeyPair getPrivate.

Prototype

public PrivateKey getPrivate() 

Source Link

Document

Returns a reference to the private key component of this key pair.

Usage

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

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

    //-------------- Set the necessary configurations

    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.cmpConfiguration.setRANameGenScheme(ALIAS, "DN");
    this.cmpConfiguration.setRANameGenParams(ALIAS, "CN");
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //---------------- Send a CMP initialization request
    AuthenticationToken admToken = null;
    final String testAdminDN = "CN=cmptestadmin,C=SE";
    final String testAdminName = "cmptestadmin";
    X509Certificate admCert = null;
    String fp = null, fp2 = null;
    try {
        KeyPair keys = KeyTools.genKeys("prime192v1", AlgorithmConstants.KEYALGORITHM_ECDSA);

        final X500Name userDN = new X500Name("CN=cmpmixuser");
        final byte[] _nonce = CmpMessageHelper.createSenderNonce();
        final byte[] _transid = CmpMessageHelper.createSenderNonce();
        final AlgorithmIdentifier pAlg = new AlgorithmIdentifier(X9ObjectIdentifiers.ecdsa_with_SHA1);
        PKIMessage req = genCertReq(issuerDN, userDN, keys, this.cacert, _nonce, _transid, false, null, null,
                null, null, pAlg, null);

        createUser(testAdminName, testAdminDN, "foo123", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE,
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        KeyPair admkeys = KeyTools.genKeys("prime192v1", AlgorithmConstants.KEYALGORITHM_ECDSA);
        admToken = createAdminToken(admkeys, testAdminName, testAdminDN, this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        admCert = getCertFromCredentials(admToken);
        fp = CertTools.getFingerprintAsString(admCert);

        CMPCertificate[] extraCert = getCMPCert(admCert);
        req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(),
                CMSSignedGenerator.DIGEST_SHA1, "BC");
        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, ALIAS);
        checkCmpResponseGeneral(resp, issuerDN, userDN, this.cacert, _nonce, _transid, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        X509Certificate cert = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
        fp2 = CertTools.getFingerprintAsString(cert);

    } finally {
        removeAuthenticationToken(admToken, admCert, testAdminName);
        this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, "cmpmixuser", ReasonFlags.unused);
        this.internalCertStoreSession.removeCertificate(fp);
        this.internalCertStoreSession.removeCertificate(fp2);
    }
    log.trace("<test23EECAuthWithRSAandECDSA()");
}

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

/**
 * Tests the possibility to use different signature algorithms in CMP requests and responses if protection algorithm 
 * is specified.//from ww w .j a v  a  2  s.  c  o  m
 * 
 * A CMP request is sent to a CA that uses ECDSA with SHA256 as signature and encryption algorithms:
 * 
 * 1. Send a CRMF request signed using ECDSA with SHA256 algorithm and expects a response signed by the same algorithm
 * 2. Send a CMP Confirm message without protection. The response is expected to be signed using ECDSA (because that's the CA's key algorithm)
 *    and SHA1 (because that's the default digest algorithm)
 * 3. Sends a CMP Revocation request signed using ECDSA with SHA256 and expects a response signed by the same algorithm.
 * 
 * @throws Exception
 */
@Test
public void test22EECAuthWithSHA256AndECDSA() throws Exception {
    log.trace(">test22EECAuthWithSHA256AndECDSA()");

    //-------------- Set the necessary configurations
    this.cmpConfiguration.setRAEEProfile(ALIAS, "ECDSAEEP");
    this.cmpConfiguration.setRACertProfile(ALIAS, "ECDSACP");
    this.cmpConfiguration.setCMPDefaultCA(ALIAS, "CmpECDSATestCA");
    this.cmpConfiguration.setRACAName(ALIAS, "CmpECDSATestCA");
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.cmpConfiguration.setRANameGenScheme(ALIAS, "DN");
    this.cmpConfiguration.setRANameGenParams(ALIAS, "CN");
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "CmpECDSATestCA");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    removeTestCA("CmpECDSATestCA");
    try {
        final CryptoTokenManagementSessionRemote cryptoTokenManagementSession = EjbRemoteHelper.INSTANCE
                .getRemoteSession(CryptoTokenManagementSessionRemote.class);
        final int cryptoTokenId = cryptoTokenManagementSession.getIdFromName("CmpECDSATestCA").intValue();
        CryptoTokenTestUtils.removeCryptoToken(ADMIN, cryptoTokenId);
    } catch (Exception e) {/* do nothing */
    }

    //---------------------- Create the test CA
    // Create catoken

    String ecdsaCADN = "CN=CmpECDSATestCA";
    String keyspec = "prime256v1";

    int cryptoTokenId = CryptoTokenTestUtils.createCryptoTokenForCA(null, "foo123".toCharArray(), true, false,
            ecdsaCADN, keyspec);
    final CAToken catoken = CaTestUtils.createCaToken(cryptoTokenId,
            AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA, AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA);
    final List<ExtendedCAServiceInfo> extendedCaServices = new ArrayList<ExtendedCAServiceInfo>(2);
    extendedCaServices.add(new KeyRecoveryCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE));
    String caname = CertTools.getPartFromDN(ecdsaCADN, "CN");
    X509CAInfo ecdsaCaInfo = new X509CAInfo(ecdsaCADN, caname, CAConstants.CA_ACTIVE,
            CertificateProfileConstants.CERTPROFILE_FIXED_ROOTCA, 3650, CAInfo.SELFSIGNED, null, catoken);
    ecdsaCaInfo.setExtendedCAServiceInfos(extendedCaServices);
    X509CA ecdsaCA = new X509CA(ecdsaCaInfo);
    ecdsaCA.setCAToken(catoken);
    // A CA certificate
    Collection<Certificate> cachain = new ArrayList<Certificate>();

    final PublicKey publicKey = this.cryptoTokenManagementProxySession
            .getPublicKey(cryptoTokenId, catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN))
            .getPublicKey();
    //final String keyalg = AlgorithmTools.getKeyAlgorithm(publicKey);
    String sigalg = AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA;
    final PrivateKey privateKey = this.cryptoTokenManagementProxySession.getPrivateKey(cryptoTokenId,
            catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));
    int keyusage = X509KeyUsage.digitalSignature + X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign;
    X509Certificate ecdsaCaCert = CertTools.genSelfCertForPurpose(ecdsaCADN, 10L, "1.1.1.1", privateKey,
            publicKey, sigalg, true, keyusage, true);
    assertNotNull(ecdsaCaCert);
    cachain.add(ecdsaCaCert);
    ecdsaCA.setCertificateChain(cachain);
    this.caSession.addCA(ADMIN, ecdsaCA);

    //-------------- Create the EndEntityProfile and the CertificateProfile
    List<Integer> availableCAs = new ArrayList<Integer>();
    availableCAs.add(Integer.valueOf(ecdsaCA.getCAId()));
    CertificateProfile cp = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    cp.setSignatureAlgorithm(AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA);
    cp.setAvailableCAs(availableCAs);
    cp.setAllowDNOverride(true);
    try {
        this.certProfileSession.addCertificateProfile(ADMIN, "ECDSACP", cp);
    } catch (CertificateProfileExistsException e) {// do nothing
    }
    int cpId = this.certProfileSession.getCertificateProfileId("ECDSACP");

    // Configure an EndEntity profile (CmpRA) with allow CN, O, C in DN
    // and rfc822Name (uncheck 'Use entity e-mail field' and check
    // 'Modifyable'), MS UPN in altNames in the end entity profile.
    EndEntityProfile eep = new EndEntityProfile(true);
    eep.setValue(EndEntityProfile.DEFAULTCERTPROFILE, 0, "" + cpId);
    eep.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, "" + cpId);
    eep.setValue(EndEntityProfile.DEFAULTCA, 0, "" + ecdsaCA.getCAId());
    eep.setValue(EndEntityProfile.AVAILCAS, 0, "" + ecdsaCA.getCAId());
    eep.setModifyable(DnComponents.RFC822NAME, 0, true);
    eep.setUse(DnComponents.RFC822NAME, 0, false); // Don't use field
    // from "email" data
    try {
        this.endEntityProfileSession.addEndEntityProfile(ADMIN, "ECDSAEEP", eep);
    } catch (EndEntityProfileExistsException e) {// do nothing
    }
    int eepId = this.endEntityProfileSession.getEndEntityProfileId("ECDSAEEP");

    //---------------- Send a CMP initialization request
    AuthenticationToken admToken = null;
    final String testAdminDN = "CN=cmptestadmin,C=SE";
    final String testAdminName = "cmptestadmin";
    X509Certificate admCert = null;
    String fp = null, fp2 = null;
    try {
        KeyPair keys = KeyTools.genKeys(keyspec, AlgorithmConstants.KEYALGORITHM_ECDSA);

        final X500Name userDN = new X500Name("CN=cmpecdsauser");
        final byte[] _nonce = CmpMessageHelper.createSenderNonce();
        final byte[] _transid = CmpMessageHelper.createSenderNonce();
        final AlgorithmIdentifier pAlg = new AlgorithmIdentifier(X9ObjectIdentifiers.ecdsa_with_SHA256);
        PKIMessage req = genCertReq(ecdsaCaInfo.getSubjectDN(), userDN, keys, ecdsaCaCert, _nonce, _transid,
                false, null, null, null, null, pAlg, null);
        createUser(testAdminName, testAdminDN, "foo123", true, ecdsaCaInfo.getCAId(), eepId, cpId);
        KeyPair admkeys = KeyTools.genKeys(keyspec, AlgorithmConstants.KEYALGORITHM_ECDSA);
        admToken = createAdminToken(admkeys, testAdminName, testAdminDN, ecdsaCA.getCAId(), eepId, cpId);
        admCert = getCertFromCredentials(admToken);
        fp = CertTools.getFingerprintAsString(admCert);

        CMPCertificate[] extraCert = getCMPCert(admCert);
        req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(),
                AlgorithmTools.getDigestFromSigAlg(pAlg.getAlgorithm().getId()), "BC");//CMSSignedGenerator.DIGEST_SHA256
        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, ALIAS);
        checkCmpResponseGeneral(resp, ecdsaCaInfo.getSubjectDN(), userDN, ecdsaCaCert, _nonce, _transid, true,
                null, X9ObjectIdentifiers.ecdsa_with_SHA256.getId());
        X509Certificate cert = checkCmpCertRepMessage(userDN, ecdsaCaCert, resp, reqId);
        fp2 = CertTools.getFingerprintAsString(cert);

        // ------------------- Send a CMP confirm message
        String hash = "foo123";
        PKIMessage confirm = genCertConfirm(userDN, ecdsaCaCert, _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, ALIAS);

        //Since pAlg was not set in the ConfirmationRequest, the default DigestAlgorithm (SHA1) will be used
        checkCmpResponseGeneral(resp, ecdsaCaInfo.getSubjectDN(), userDN, ecdsaCaCert, _nonce, _transid, true,
                null, X9ObjectIdentifiers.ecdsa_with_SHA1.getId());
        checkCmpPKIConfirmMessage(userDN, ecdsaCaCert, resp);

        //-------------------------  Send a CMP revocation request
        PKIMessage rev = genRevReq(ecdsaCaInfo.getSubjectDN(), userDN, cert.getSerialNumber(), ecdsaCaCert,
                _nonce, _transid, true, pAlg, null);
        assertNotNull(rev);
        rev = CmpMessageHelper.buildCertBasedPKIProtection(rev, extraCert, admkeys.getPrivate(),
                AlgorithmTools.getDigestFromSigAlg(pAlg.getAlgorithm().getId()), "BC");
        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, ALIAS);
        checkCmpResponseGeneral(resp, ecdsaCaInfo.getSubjectDN(), userDN, ecdsaCaCert, _nonce, _transid, true,
                null, X9ObjectIdentifiers.ecdsa_with_SHA256.getId());
        int revStatus = checkRevokeStatus(ecdsaCaInfo.getSubjectDN(), CertTools.getSerialNumber(cert));
        assertNotEquals("Revocation request failed to revoke the certificate", RevokedCertInfo.NOT_REVOKED,
                revStatus);

    } finally {
        try {
            removeAuthenticationToken(admToken, admCert, testAdminName);
        } catch (Exception e) {
            //NOPMD: Ignore
        }
        try {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, "cmpecdsauser", ReasonFlags.unused);
        } catch (Exception e) {
            //NOPMD: Ignore
        }
        this.internalCertStoreSession.removeCertificate(fp);
        this.internalCertStoreSession.removeCertificate(fp2);
        this.endEntityProfileSession.removeEndEntityProfile(ADMIN, "ECDSAEEP");
        this.certProfileSession.removeCertificateProfile(ADMIN, "ECDSACP");

        removeTestCA("CmpECDSATestCA");
    }
    log.trace("<test22EECAuthWithSHA256AndECDSA()");

}

From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java

/**
 * Generates a self signed certificate using the given properties.
 *
 * @param commonName the subject's common name
 * @param organization the subject's organization name
 * @param organizationUnit the subject's organization unit name
 * @param stateOrProvince the subject's state or province
 * @param country the subject's country code
 * @param locality the subject's locality
 * @param algorithm the algorithm to use
 * @param keySize the keysize to use//from  w w w  .j a v a2 s  . c  om
 * @param signatureAlgorithm the signature algorithm to use
 * @param validFrom when the certificate is valid from
 * @param validTo when the certificate is valid until
 * @return The generated certificate
 * @throws Exception
 */
protected Pair<X509Certificate, PrivateKey> generateCertificate(String commonName, String organization,
        String organizationUnit, String stateOrProvince, String country, String locality, String algorithm,
        int keySize, String signatureAlgorithm, String validFrom, String validTo) throws Exception {

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm); // "RSA","BC"
    keyPairGenerator.initialize(keySize);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    // Generate self-signed certificate
    X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
    builder.addRDN(BCStyle.C, country);
    builder.addRDN(BCStyle.ST, stateOrProvince);
    builder.addRDN(BCStyle.L, locality);
    builder.addRDN(BCStyle.OU, organizationUnit);
    builder.addRDN(BCStyle.O, organization);
    builder.addRDN(BCStyle.CN, commonName);

    Date notBefore = null;
    Date notAfter = null;
    if (validFrom == null) {
        notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30);
    } else {
        DateTime notBeforeDateTime = DateUtil.getDateUtil().parseIfDate(validFrom);
        if (notBeforeDateTime == null) {
            throw new InternalServerErrorException("Invalid date format for 'validFrom' property");
        } else {
            notBefore = notBeforeDateTime.toDate();
        }
    }
    if (validTo == null) {
        Calendar date = Calendar.getInstance();
        date.setTime(new Date());
        date.add(Calendar.YEAR, 10);
        notAfter = date.getTime();
    } else {
        DateTime notAfterDateTime = DateUtil.getDateUtil().parseIfDate(validTo);
        if (notAfterDateTime == null) {
            throw new InternalServerErrorException("Invalid date format for 'validTo' property");
        } else {
            notAfter = notAfterDateTime.toDate();
        }
    }

    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());

    X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(builder.build(), serial, notBefore,
            notAfter, builder.build(), keyPair.getPublic());

    ContentSigner sigGen = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC)
            .build(keyPair.getPrivate());

    X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC)
            .getCertificate(v3CertGen.build(sigGen));
    cert.checkValidity(new Date());
    cert.verify(cert.getPublicKey());

    return Pair.of(cert, keyPair.getPrivate());
}

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

/**
 * 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  av a2 s  .  c om*/
 * - 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

/**
 * 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.
 * /*from   www  .ja v a 2 s.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 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:mitm.common.security.certificate.impl.StandardX509CertificateBuilderTest.java

@Test
public void testGenerateSelfSignedV3Certificate() throws Exception {
    X509CertificateBuilder certificateBuilder = new StandardX509CertificateBuilder("BC", "BC");

    KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA");

    keyPairGenerator.initialize(2048, randomSource);

    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    X500PrincipalBuilder issuerBuilder = new X500PrincipalBuilder();

    issuerBuilder.setCommonName("Martijn Brinkers");
    issuerBuilder.setCountryCode("NL");
    issuerBuilder.setEmail("test@example.com", "test2@example.com");
    issuerBuilder.setGivenName("Martijn");
    issuerBuilder.setSurname("Brinkers");
    issuerBuilder.setLocality("Amsterdam");
    issuerBuilder.setOrganisation("None");
    issuerBuilder.setState("NH");

    AltNamesBuilder altNamesBuider = new AltNamesBuilder();

    altNamesBuider.setRFC822Names("m.brinkers@pobox.com");
    altNamesBuider.setDNSNames("example.com");

    X500Principal issuer = issuerBuilder.buildPrincipal();
    GeneralNames altNames = altNamesBuider.buildAltNames();

    Set<KeyUsageType> keyUsage = new HashSet<KeyUsageType>();

    keyUsage.add(KeyUsageType.DIGITALSIGNATURE);
    keyUsage.add(KeyUsageType.KEYENCIPHERMENT);
    keyUsage.add(KeyUsageType.NONREPUDIATION);

    Set<ExtendedKeyUsageType> extendedKeyUsage = new HashSet<ExtendedKeyUsageType>();

    extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH);
    extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION);

    Date notBefore = DateUtils.addHours(new Date(), -1);
    Date notAfter = DateUtils.addYears(new Date(), 10);

    certificateBuilder.setSubject(issuer);
    certificateBuilder.setIssuer(issuer);
    certificateBuilder.setAltNames(altNames, true);
    certificateBuilder.setKeyUsage(keyUsage, true);
    certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, true);
    certificateBuilder.setNotBefore(notBefore);
    certificateBuilder.setNotAfter(notAfter);
    certificateBuilder.setPublicKey(keyPair.getPublic());
    certificateBuilder.setSerialNumber(new BigInteger("1"));
    certificateBuilder.setSignatureAlgorithm("SHA256WithRSA");
    certificateBuilder.setIsCA(true, true /* critical */);
    certificateBuilder.setPathLengthConstraint(5);

    Set<String> crlDistPoints = new HashSet<String>();
    crlDistPoints.add("http://example.com");
    crlDistPoints.add("123");

    certificateBuilder.setCRLDistributionPoints(crlDistPoints);

    X509Certificate certificate = certificateBuilder.generateCertificate(keyPair.getPrivate(), null);

    assertNotNull(certificate);// w  ww. j  a  v  a 2  s. c o  m

    File file = new File(tempDir, "testGenerateSelfSignedV3Certificate.cer");

    CertificateUtils.writeCertificate(certificate, file);

    X509CertificateInspector certInspector = new X509CertificateInspector(certificate);

    assertEquals(
            "EMAILADDRESS=test2@example.com, EMAILADDRESS=test@example.com, GIVENNAME=Martijn, "
                    + "SURNAME=Brinkers, CN=Martijn Brinkers, O=None, L=Amsterdam, ST=NH, C=NL",
            certInspector.getSubjectFriendly());

    assertEquals(certInspector.getIssuerFriendly(), certInspector.getSubjectFriendly());

    AltNamesInspector altNamesInspector = new AltNamesInspector(certificate.getSubjectAlternativeNames());

    List<String> rFC822Names = altNamesInspector.getRFC822Names();

    assertEquals(1, rFC822Names.size());
    assertEquals("m.brinkers@pobox.com", rFC822Names.get(0));

    List<String> dNSNames = altNamesInspector.getDNSNames();

    assertEquals(1, dNSNames.size());
    assertEquals("example.com", dNSNames.get(0));

    assertEquals(3, certInspector.getKeyUsage().size());
    assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.DIGITALSIGNATURE));
    assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.KEYENCIPHERMENT));
    assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.NONREPUDIATION));

    assertEquals(2, certInspector.getExtendedKeyUsage().size());
    assertTrue(certInspector.getExtendedKeyUsage().contains(ExtendedKeyUsageType.CLIENTAUTH));
    assertTrue(certInspector.getExtendedKeyUsage().contains(ExtendedKeyUsageType.EMAILPROTECTION));

    // we cannot compare the dates because of encoding we loose some detail so check if within 1 sec
    assertTrue(Math.abs(notAfter.getTime() - certificate.getNotAfter().getTime()) < 1000);
    assertTrue(Math.abs(notBefore.getTime() - certificate.getNotBefore().getTime()) < 1000);

    assertEquals("1", certInspector.getSerialNumberHex());

    assertEquals("SHA256WITHRSA", certificate.getSigAlgName());

    assertTrue(certInspector.isCA());
    assertEquals(5, certInspector.getBasicConstraints().getPathLenConstraint().intValue());

    Set<String> crlDistPointsCert = CRLDistributionPointsInspector
            .getURIDistributionPointNames(certInspector.getCRLDistibutionPoints());

    assertTrue(crlDistPointsCert.contains("http://example.com"));
    assertTrue(crlDistPointsCert.contains("123"));
}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

private X509Certificate generateV3Certificate(KeyPair pair, String certSubjectDN, Calendar before,
        Calendar expiry) throws CryptoException {
    X509V3CertificateGenerator cert = new X509V3CertificateGenerator();

    /* Set the certificate serial number to a random number */
    Random rand = new Random();
    rand.setSeed(System.currentTimeMillis());

    /* Generates a number between 0 and 2^32 as the serial */
    BigInteger serial = BigInteger.valueOf(rand.nextInt(Integer.MAX_VALUE));
    logger.info("Setting X509 Cert Serial to: " + serial);

    cert.setSerialNumber(serial);/*from ww w . j a  v  a 2 s.c om*/

    /* Set the certificate issuer */
    cert.setIssuerDN(new X500Principal(this.certIssuerDN));

    /* Set the start of valid period. */
    cert.setNotBefore(before.getTime());

    /* Set the certificate expiry date. */
    cert.setNotAfter(expiry.getTime());

    /* Set the subject */
    cert.setSubjectDN(new X500Principal(certSubjectDN));

    cert.setPublicKey(pair.getPublic());

    /* Signature algorithm, this may need to be changed if not all hosts have SHA256 and RSA implementations */
    cert.setSignatureAlgorithm("SHA512withRSA");

    cert.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    /* Only for signing */
    cert.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign));
    cert.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    /* Set a contact email address for the issuer */
    cert.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, this.certIssuerEmail)));

    logger.debug("Generating X509Certificate for key pair: " + pair);

    try {
        /* Use the BouncyCastle provider to actually generate the X509Certificate now */
        return cert.generateX509Certificate(pair.getPrivate(), "BC");
    } catch (InvalidKeyException e) {
        this.logger.error("InvalidKeyException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (NoSuchProviderException e) {
        this.logger.error("NoSuchProviderException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (SecurityException e) {
        this.logger.error("SecurityException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (SignatureException e) {
        this.logger.error("SignatureException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    }

}

From source file:com.netscape.cms.servlet.csadmin.ConfigurationUtils.java

public static KeyPair createRSAKeyPair(String token, int keysize, IConfigStore config, String ct)
        throws Exception {

    logger.debug("ConfigurationUtils.createRSAKeyPair(" + token + ")");

    KeyPair pair = null;
    do {//from ww w  .ja  va2  s . c o  m
        pair = CryptoUtil.generateRSAKeyPair(token, keysize);
        byte id[] = ((org.mozilla.jss.crypto.PrivateKey) pair.getPrivate()).getUniqueID();
        String kid = CryptoUtil.encodeKeyID(id);

        // try to locate the private key
        org.mozilla.jss.crypto.PrivateKey privk = CryptoUtil.findPrivateKeyFromID(CryptoUtil.decodeKeyID(kid));

        if (privk == null) {
            logger.debug("Found bad RSA key id " + kid);
            pair = null;
        }
    } while (pair == null);

    return pair;
}

From source file:org.ejbca.ui.cmpclient.commands.KeyUpdateRequestCommand.java

@Override
public PKIMessage generatePKIMessage(ParameterContainer parameters) throws Exception {
    boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY));
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));
    boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY);

    if (verbose) {
        log.info("Creating KeyUpdate request with: SubjectDN=" + userDN.toString());
        log.info("Creating KeyUpdate request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating KeyUpdate request with: IncludePopo=" + includePopo);
    }//from   w  w  w. j  a va 2s  .  co  m

    byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce();
    byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce();
    KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();

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

    myCertTemplate.setValidity(myOptionalValidity);

    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
    } finally {
        dIn.close();
    }

    myCertTemplate.setSubject(userDN);

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

    // POPO
    /*
     * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8,
     * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 }));
     * 
     * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new
     * byte[] { 44 }), 2); //take choice pos tag 2
     * 
     * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput(
     * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2,
     * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 }));
     */
    ProofOfPossession myProofOfPossession = null;
    if (includePopo) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DEROutputStream mout = new DEROutputStream(baos);
        mout.writeObject(myCertRequest);
        mout.close();
        byte[] popoProtectionBytes = baos.toByteArray();
        String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm())
                .getId();
        Signature sig = Signature.getInstance(sigalg);
        sig.initSign(keys.getPrivate());
        sig.update(popoProtectionBytes);

        DERBitString bs = new DERBitString(sig.sign());

        POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null,
                new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs);
        myProofOfPossession = new ProofOfPossession(myPOPOSigningKey);
    } else {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    }

    // myCertReqMsg.addRegInfo(new AttributeTypeAndValue(new
    // ASN1ObjectIdentifier("1.3.6.2.2.2.2.3.1"), new
    // DERInteger(1122334455)));
    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String(""));
    AttributeTypeAndValue[] avs = { av };

    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(issuerDN));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(null);

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, myCertReqMessages); // Key Update Request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);

    return myPKIMessage;
}

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

/** Test CMP initial request against EJBCA CMP in client mode (operationmode=normal) using End Entity certificate signature authentication, 
 * i.e. the request is signed by a certificate of the same end entity making the request, and this signature is used for authenticating the end entity.
 * Test://ww  w  .j  av a 2  s  .  co  m
 * - Request signed by a fake certificate, i.e. one that is not in the database (FAIL)
 * - Request signed by a certificate that beloongs to another user (FAIL)
 * - Request signed by a proper certificate but where user status is not NEW (FAIL)
 * - Request signed by a proper, but revoked certificate (FAIL)
 * - A working request signed by a proper, unrevoked certificate and user status is NEW (SUCCESS)
 * 
 * @throws Exception on some errors
 */
@Test
public void test18CrmfReqClientModeEESignature() throws Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "-");
    this.cmpConfiguration.setRAMode(ALIAS, false);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    final X500Name testUserDN = new X500Name("CN=cmptestuser16,C=SE");
    final String testUsername = "cmptestuser16";
    final String otherUserDN = "CN=cmptestotheruser16,C=SE";
    final String otherUsername = "cmptestotheruser16";
    String fingerprint = null;
    String fingerprint2 = null;
    String fingerprint3 = null;
    try {
        KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        KeyPair fakeKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        createUser(testUsername, testUserDN.toString(), "foo123", true, this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        // A real certificate that can be used to sign the message
        Certificate cert = this.signSession.createCertificate(ADMIN, testUsername, "foo123",
                new PublicKeyWrapper(keys.getPublic()));
        fingerprint = CertTools.getFingerprintAsString(cert);
        // A fake certificate that should not be valid
        Certificate fakeCert = CertTools.genSelfCert(testUserDN.toString(), 30, null, fakeKeys.getPrivate(),
                fakeKeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false);

        // Step 1 sign with fake certificate, should not be valid as end entity authentication
        {
            AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
            PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid,
                    false, null, null, null, null, pAlg, null);
            assertNotNull("Generating CrmfRequest failed.", msg);
            CMPCertificate[] extraCert = getCMPCert(fakeCert);
            msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, fakeKeys.getPrivate(),
                    pAlg.getAlgorithm().getId(), "BC");
            assertNotNull(msg);
            //******************************************''''''
            final Signature sig = Signature
                    .getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC");
            sig.initVerify(fakeCert.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, ALIAS);
            // This should have failed
            checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert,
                    msg.getHeader().getSenderNonce().getOctets(),
                    msg.getHeader().getTransactionID().getOctets(), false, null,
                    PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
            ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
            PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
            try {
                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);
            } finally {
                inputStream.close();
            }
        }
        // Step 2, sign the request with a certificate that does not belong to the user
        {
            KeyPair otherKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
            createUser(otherUsername, otherUserDN, "foo123", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE,
                    CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
            // A real certificate that can be used to sign the message
            Certificate othercert = this.signSession.createCertificate(ADMIN, otherUsername, "foo123",
                    new PublicKeyWrapper(otherKeys.getPublic()));
            fingerprint2 = CertTools.getFingerprintAsString(cert);
            AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
            PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid,
                    false, null, null, null, null, pAlg, null);
            assertNotNull("Generating CrmfRequest failed.", msg);
            CMPCertificate[] extraCert = getCMPCert(othercert);
            msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, otherKeys.getPrivate(),
                    pAlg.getAlgorithm().getId(), "BC");
            assertNotNull(msg);
            //******************************************''''''
            final Signature sig = Signature
                    .getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC");
            sig.initVerify(othercert.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, ALIAS);
            // This should have failed
            checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert,
                    msg.getHeader().getSenderNonce().getOctets(),
                    msg.getHeader().getTransactionID().getOctets(), false, null,
                    PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
            ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
            try {
                PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
                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 End Entity certificate attached to the PKIMessage in the extraCert field does not belong to user '"
                        + testUsername + "'";
                assertEquals(expectedErrMsg, errMsg);
            } finally {
                inputStream.close();
            }
        }

        // Step 3 sign with the real certificate, but user status is not NEW
        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false,
                null, null, null, null, pAlg, null);
        assertNotNull("Generating CrmfRequest failed.", msg);
        CMPCertificate[] extraCert = getCMPCert(cert);
        msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, keys.getPrivate(),
                pAlg.getAlgorithm().getId(), "BC");
        assertNotNull(msg);
        //******************************************''''''
        final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(),
                "BC");
        sig.initVerify(cert.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, ALIAS);
        checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert,
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        // This should have failed
        ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
        try {
            PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
            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 = "Got request with status GENERATED (40), NEW, FAILED or INPROCESS required: cmptestuser16.";
            assertEquals(expectedErrMsg, errMsg);

            // Step 4 now set status to NEW, and a clear text password, then it should finally work
            createUser(testUsername, testUserDN.toString(), "randompasswordhere", true, this.caid,
                    SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
            // Send request and receive response
            final byte[] resp2 = sendCmpHttp(ba, 200, ALIAS);
            CertReqMessages ir = (CertReqMessages) msg.getBody().getContent();
            Certificate cert2 = checkCmpCertRepMessage(testUserDN, this.cacert, resp2,
                    ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
            assertNotNull("CrmfRequest did not return a certificate", cert2);
            fingerprint3 = CertTools.getFingerprintAsString(cert2);

            // Step 5, revoke the certificate and try again
            {
                this.certificateStoreSession.setRevokeStatus(ADMIN, cert,
                        RevokedCertInfo.REVOCATION_REASON_CESSATIONOFOPERATION, null);
                final byte[] resp3 = sendCmpHttp(ba, 200, ALIAS);
                // This should have failed
                checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert,
                        msg.getHeader().getSenderNonce().getOctets(),
                        msg.getHeader().getTransactionID().getOctets(), false, null,
                        PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
                ASN1InputStream inputStream3 = new ASN1InputStream(new ByteArrayInputStream(resp3));
                try {
                    PKIMessage respObject3 = PKIMessage.getInstance(inputStream3.readObject());
                    assertNotNull(respObject);
                    PKIBody body3 = respObject3.getBody();
                    assertEquals(23, body3.getType());
                    err = (ErrorMsgContent) body3.getContent();
                    String errMsg3 = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
                    String expectedErrMsg3 = "The certificate attached to the PKIMessage in the extraCert field is not active.";
                    assertEquals(expectedErrMsg3, errMsg3);
                } finally {
                    inputStream3.close();
                }
            }
        } finally {
            inputStream.close();
        }

    } finally {
        try {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused);
        } catch (Exception e) {// do nothing
        }

        try {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, otherUsername, ReasonFlags.unused);
        } catch (Exception e) {// do nothing
        }

        this.internalCertStoreSession.removeCertificate(fingerprint);
        this.internalCertStoreSession.removeCertificate(fingerprint2);
        this.internalCertStoreSession.removeCertificate(fingerprint3);
    }
}