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.ws.CommonEjbcaWS.java

protected void errorOnGeneratePkcs10() throws Exception {

    // Add a user for this test purpose.
    UserDataVOWS user1 = new UserDataVOWS();
    user1.setUsername("WSTESTUSER30");
    user1.setPassword("foo1234");
    user1.setClearPwd(true);// ww w .j a  va  2s .  c  o m
    user1.setSubjectDN("CN=WSTESTUSER30");
    user1.setEmail(null);
    user1.setSubjectAltName(null);
    user1.setStatus(UserDataVOWS.STATUS_NEW);
    user1.setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED);
    user1.setEndEntityProfileName("EMPTY");
    user1.setCertificateProfileName("ENDUSER");
    user1.setCaName(getAdminCAName());
    ejbcaraws.editUser(user1);

    KeyPair keys = null;
    PKCS10CertificationRequest pkcs10 = null;
    ErrorCode errorCode = null;

    // ///// Check Error.LOGIN_ERROR ///////
    keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
    pkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
            CertTools.stringToBcX500Name("CN=WSTESTUSER30"), keys.getPublic(), new DERSet(), keys.getPrivate(),
            null);

    try {
        ejbcaraws.pkcs10Request("WSTESTUSER30", PASSWORD, new String(Base64.encode(pkcs10.getEncoded())), null,
                CertificateHelper.RESPONSETYPE_CERTIFICATE);
    } catch (EjbcaException_Exception e) {
        errorCode = e.getFaultInfo().getErrorCode();
    }

    assertNotNull("error code should not be null", errorCode);
    assertEquals(errorCode.getInternalErrorCode(), org.cesecore.ErrorCode.LOGIN_ERROR.getInternalErrorCode());

    errorCode = null;

    // ///// Check Error.USER_WRONG_STATUS ///////
    user1.setStatus(EndEntityConstants.STATUS_REVOKED);
    ejbcaraws.editUser(user1);

    keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
    pkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
            CertTools.stringToBcX500Name("CN=WSTESTUSER30"), keys.getPublic(), new DERSet(), keys.getPrivate(),
            null);

    try {
        ejbcaraws.pkcs10Request("WSTESTUSER30", "foo1234", new String(Base64.encode(pkcs10.getEncoded())), null,
                CertificateHelper.RESPONSETYPE_CERTIFICATE);
    } catch (EjbcaException_Exception e) {
        errorCode = e.getFaultInfo().getErrorCode();
    }

    assertNotNull("error code should not be null", errorCode);
    assertEquals(errorCode.getInternalErrorCode(),
            org.cesecore.ErrorCode.USER_WRONG_STATUS.getInternalErrorCode());

}

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

/**
 * Sends a KeyUpdateRequest by an EndEntity concerning its own certificate in RA mode. 
 * A CMP error message is expected and no certificate renewal.
 * /*  ww w  . ja  v  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

/**
 * A "Happy Path" test. Sends a KeyUpdateRequest and receives a new certificate.
 * // w ww  .  j ava2  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.
 * - 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
 *      - Obtains the certificate from the response
 *      - Checks that the obtained certificate has the right subjectDN and issuerDN
 * 
 * @throws Exception
 */
@Test
public void test01KeyUpdateRequestOK() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">test01KeyUpdateRequestOK");
    }

    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);
    CertReqMessages kur = (CertReqMessages) req.getBody().getContent();
    int reqId = kur.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    CMPCertificate[] extraCert = getCMPCert(certificate);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(),
            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, true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkKurCertRepMessage(this.userDN, this.cacert, resp, reqId);
    assertNotNull("Failed to renew the certificate", cert);
    assertTrue("The new certificate's keys are incorrect.", cert.getPublicKey().equals(keys.getPublic()));

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

}

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

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

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

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

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

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, true, null,
            PKCSObjectIdentifiers.sha256WithRSAEncryption.getId());
    X509Certificate cert = checkKurCertRepMessage(this.userDN, this.cacert, resp, reqId);
    assertNotNull("Failed to renew the certificate", cert);
    assertTrue("The new certificate's keys are incorrect.", cert.getPublicKey().equals(keys.getPublic()));

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

}

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

public static void storeKeyPair(IConfigStore config, String tag, KeyPair pair)
        throws TokenException, EBaseException {

    logger.debug("ConfigurationUtils: storeKeyPair(" + tag + ")");

    PublicKey publicKey = pair.getPublic();

    if (publicKey instanceof RSAPublicKey) {

        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;

        byte modulus[] = rsaPublicKey.getModulus().toByteArray();
        config.putString(PCERT_PREFIX + tag + ".pubkey.modulus", CryptoUtil.byte2string(modulus));

        byte exponent[] = rsaPublicKey.getPublicExponent().toByteArray();
        config.putString(PCERT_PREFIX + tag + ".pubkey.exponent", CryptoUtil.byte2string(exponent));

    } else { // ECC

        logger.debug("ConfigurationUtils: Public key class: " + publicKey.getClass().getName());
        byte encoded[] = publicKey.getEncoded();
        config.putString(PCERT_PREFIX + tag + ".pubkey.encoded", CryptoUtil.byte2string(encoded));
    }/*from w  w w .  j  a  v  a 2s.c  o  m*/

    PrivateKey privateKey = (PrivateKey) pair.getPrivate();
    byte id[] = privateKey.getUniqueID();
    String kid = CryptoUtil.encodeKeyID(id);
    config.putString(PCERT_PREFIX + tag + ".privkey.id", kid);

    String keyAlgo = config.getString(PCERT_PREFIX + tag + ".signingalgorithm");
    setSigningAlgorithm(tag, keyAlgo, config);
}

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

/**
 * Sends a KeyUpdateRequest concerning a revoked certificate. A CMP error message is expected and no certificate renewal.
 * //from  w  ww  . java  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.ejb.ca.caadmin.CAAdminSessionBean.java

/**
 * Method that import CA token keys from a P12 file. Was originally used when upgrading from old EJBCA versions. Only supports SHA1 and SHA256
 * with RSA or ECDSA and SHA1 with DSA.//from www  .j a  v  a  2s.c  om
 * @throws OperatorCreationException 
 * @throws AuthorizationDeniedException 
 */
private CAToken importKeysToCAToken(AuthenticationToken authenticationToken, String authenticationCode,
        Properties caTokenProperties, PrivateKey privatekey, PublicKey publickey,
        PrivateKey privateEncryptionKey, PublicKey publicEncryptionKey, Certificate[] caSignatureCertChain,
        int caId) throws CryptoTokenAuthenticationFailedException, IllegalCryptoTokenException,
        OperatorCreationException, AuthorizationDeniedException {
    // If we don't give an authentication code, perhaps we have autoactivation enabled
    if (StringUtils.isEmpty(authenticationCode)) {
        String msg = intres.getLocalizedMessage("token.authcodemissing", Integer.valueOf(caId));
        log.info(msg);
        throw new CryptoTokenAuthenticationFailedException(msg);
    }
    if (caTokenProperties == null) {
        caTokenProperties = new Properties();
    }

    try {
        // Currently only RSA keys are supported
        KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
        keystore.load(null, null);

        // The CAs certificate is first in chain
        Certificate cacert = caSignatureCertChain[0];
        // Assume that the same hash algorithm is used for signing that was used to sign this CA cert
        String signatureAlgorithm = AlgorithmTools.getSignatureAlgorithm(cacert);
        String keyAlg = AlgorithmTools.getKeyAlgorithm(publickey);
        if (keyAlg == null) {
            throw new IllegalCryptoTokenException(
                    "Unknown public key type: " + publickey.getAlgorithm() + " (" + publickey.getClass() + ")");
        }

        // import sign keys.
        final Certificate[] certchain = new Certificate[1];
        certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, privatekey, publickey, signatureAlgorithm,
                true);

        keystore.setKeyEntry(CAToken.SOFTPRIVATESIGNKEYALIAS, privatekey, null, certchain);

        // generate enc keys.
        // Encryption keys must be RSA still
        final String encryptionAlgorithm = AlgorithmTools.getEncSigAlgFromSigAlg(signatureAlgorithm);
        keyAlg = AlgorithmTools.getKeyAlgorithmFromSigAlg(encryptionAlgorithm);
        final String enckeyspec = "2048";
        KeyPair enckeys = null;
        if (publicEncryptionKey == null || privateEncryptionKey == null) {
            enckeys = KeyTools.genKeys(enckeyspec, keyAlg);
        } else {
            enckeys = new KeyPair(publicEncryptionKey, privateEncryptionKey);
        }
        // generate dummy certificate
        certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, enckeys.getPrivate(),
                enckeys.getPublic(), encryptionAlgorithm, true);
        keystore.setKeyEntry(CAToken.SOFTPRIVATEDECKEYALIAS, enckeys.getPrivate(), null, certchain);

        // Set the token properties
        caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING,
                CAToken.SOFTPRIVATESIGNKEYALIAS);
        caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING,
                CAToken.SOFTPRIVATESIGNKEYALIAS);
        caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING,
                CAToken.SOFTPRIVATEDECKEYALIAS);

        // Write the keystore to byte[] that we can feed to crypto token factory
        final char[] authCode = authenticationCode.toCharArray();
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        keystore.store(baos, authCode);

        // Now we have the PKCS12 keystore, from this we can create the CAToken
        final Properties cryptoTokenProperties = new Properties();
        int cryptoTokenId;
        try {
            cryptoTokenId = createCryptoTokenWithUniqueName(authenticationToken, "ImportedCryptoToken" + caId,
                    SoftCryptoToken.class.getName(), cryptoTokenProperties, baos.toByteArray(), authCode);
        } catch (NoSuchSlotException e1) {
            throw new RuntimeException(
                    "Attempte to define a slot for a soft crypto token. This should not happen.");
        }
        final CAToken catoken = new CAToken(cryptoTokenId, caTokenProperties);
        // If this is a CVC CA we need to find out the sequence
        String sequence = CAToken.DEFAULT_KEYSEQUENCE;
        if (cacert instanceof CardVerifiableCertificate) {
            CardVerifiableCertificate cvccacert = (CardVerifiableCertificate) cacert;
            log.debug("Getting sequence from holderRef in CV certificate.");
            try {
                sequence = cvccacert.getCVCertificate().getCertificateBody().getHolderReference().getSequence();
            } catch (NoSuchFieldException e) {
                log.error("Can not get sequence from holderRef in CV certificate, using default sequence.");
            }
        }
        log.debug("Setting sequence " + sequence);
        catoken.setKeySequence(sequence);
        log.debug("Setting default sequence format " + StringTools.KEY_SEQUENCE_FORMAT_NUMERIC);
        catoken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC);
        catoken.setSignatureAlgorithm(signatureAlgorithm);
        catoken.setEncryptionAlgorithm(encryptionAlgorithm);
        return catoken;
    } catch (KeyStoreException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (NoSuchProviderException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (CertificateException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (IOException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (IllegalStateException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (CryptoTokenOfflineException e) {
        throw new IllegalCryptoTokenException(e);
    }
}

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

private PKCS10CertificationRequest getP10Request() throws Exception {
    final KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    // Make a PKCS10 request with extensions
    ASN1EncodableVector attributes = new ASN1EncodableVector();
    // Add a custom extension (dummy)
    ASN1EncodableVector attr = new ASN1EncodableVector();
    attr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    extgen.addExtension(new ASN1ObjectIdentifier("1.2.3.4"), false, new DEROctetString("foo123".getBytes()));
    Extensions exts = extgen.generate();
    attr.add(new DERSet(exts));
    attributes.add(new DERSequence(attr));
    PKCS10CertificationRequest pkcs10 = CertTools.genPKCS10CertificationRequest("SHA1WithRSA",
            CertTools.stringToBcX500Name("CN=NOUSED"), keys.getPublic(), new DERSet(attributes),
            keys.getPrivate(), null);
    return pkcs10;
}

From source file:com.netscape.ca.CertificateAuthority.java

/**
 * Create a new lightweight authority signed by this authority.
 *
 * This method DOES NOT add the new CA to caMap; it is the
 * caller's responsibility.// www  .  j a  v  a2  s .  c  o  m
 */
public ICertificateAuthority createSubCA(IAuthToken authToken, String subjectDN, String description)
        throws EBaseException {

    ensureReady();

    // check requested DN
    X500Name subjectX500Name = null;
    try {
        subjectX500Name = new X500Name(subjectDN);
    } catch (IOException e) {
        throw new IllegalArgumentException("Invalid Subject DN: " + subjectDN);
    }
    ensureAuthorityDNAvailable(subjectX500Name);

    // generate authority ID and nickname
    AuthorityID aid = new AuthorityID();
    String aidString = aid.toString();
    String nickname = hostCA.getNickname() + " " + aidString;

    // build database entry
    String dn = "cn=" + aidString + "," + authorityBaseDN();
    logger.debug("createSubCA: DN = " + dn);
    String parentDNString = null;
    try {
        parentDNString = mName.toLdapDNString();
    } catch (IOException e) {
        throw new EBaseException("Failed to convert issuer DN to string: " + e);
    }

    String thisClone = CMS.getEEHost() + ":" + CMS.getEESSLPort();

    LDAPAttribute[] attrs = { new LDAPAttribute("objectclass", "authority"), new LDAPAttribute("cn", aidString),
            new LDAPAttribute("authorityID", aidString), new LDAPAttribute("authorityKeyNickname", nickname),
            new LDAPAttribute("authorityKeyHost", thisClone), new LDAPAttribute("authorityEnabled", "TRUE"),
            new LDAPAttribute("authorityDN", subjectDN),
            new LDAPAttribute("authorityParentDN", parentDNString) };
    LDAPAttributeSet attrSet = new LDAPAttributeSet(attrs);
    if (this.authorityID != null)
        attrSet.add(new LDAPAttribute("authorityParentID", this.authorityID.toString()));
    if (description != null)
        attrSet.add(new LDAPAttribute("description", description));
    LDAPEntry ldapEntry = new LDAPEntry(dn, attrSet);

    addAuthorityEntry(aid, ldapEntry);

    X509CertImpl cert = null;

    try {
        // Generate signing key
        CryptoManager cryptoManager = CryptoManager.getInstance();
        // TODO read PROP_TOKEN_NAME config
        CryptoToken token = cryptoManager.getInternalKeyStorageToken();
        // TODO algorithm parameter
        KeyPairGenerator gen = token.getKeyPairGenerator(KeyPairAlgorithm.RSA);
        gen.initialize(2048);
        KeyPair keypair = gen.genKeyPair();
        PublicKey pub = keypair.getPublic();
        X509Key x509key = CryptoUtil.convertPublicKeyToX509Key(pub);

        // Create pkcs10 request
        logger.debug("createSubCA: creating pkcs10 request");
        PKCS10 pkcs10 = new PKCS10(x509key);
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(keypair.getPrivate());
        pkcs10.encodeAndSign(new X500Signer(signature, subjectX500Name));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        pkcs10.print(new PrintStream(out));
        String pkcs10String = out.toString();

        // Sign certificate
        Locale locale = Locale.getDefault();
        String profileId = "caCACert";
        IProfileSubsystem ps = (IProfileSubsystem) CMS.getSubsystem(IProfileSubsystem.ID);
        IProfile profile = ps.getProfile(profileId);
        ArgBlock argBlock = new ArgBlock();
        argBlock.set("cert_request_type", "pkcs10");
        argBlock.set("cert_request", pkcs10String);
        CertEnrollmentRequest certRequest = CertEnrollmentRequestFactory.create(argBlock, profile, locale);
        EnrollmentProcessor processor = new EnrollmentProcessor("createSubCA", locale);
        Map<String, Object> resultMap = processor.processEnrollment(certRequest, null, authorityID, null,
                authToken);
        IRequest requests[] = (IRequest[]) resultMap.get(CAProcessor.ARG_REQUESTS);
        IRequest request = requests[0];
        Integer result = request.getExtDataInInteger(IRequest.RESULT);
        if (result != null && !result.equals(IRequest.RES_SUCCESS))
            throw new EBaseException(
                    "createSubCA: certificate request submission resulted in error: " + result);
        RequestStatus requestStatus = request.getRequestStatus();
        if (requestStatus != RequestStatus.COMPLETE) {
            // The request did not complete.  Inference: something
            // incorrect in the request (e.g. profile constraint
            // violated).
            String msg = "Failed to issue CA certificate. Final status: " + requestStatus + ".";
            String errorMsg = request.getExtDataInString(IRequest.ERROR);
            if (errorMsg != null)
                msg += " Additional info: " + errorMsg;
            throw new BadRequestDataException(msg);
        }

        // Add certificate to nssdb
        cert = request.getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT);
        cryptoManager.importCertPackage(cert.getEncoded(), nickname);
    } catch (Exception e) {
        // something went wrong; delete just-added entry
        logger.error("Error creating lightweight CA certificate: " + e.getMessage(), e);

        try {
            deleteAuthorityEntry(aid);
        } catch (ELdapException e2) {
            // we are about to throw ECAException, so just
            // log this error.
            logger.error("Error deleting new authority entry after failure during certificate generation: "
                    + e2.getMessage(), e2);
        }
        if (e instanceof BadRequestDataException)
            throw (BadRequestDataException) e; // re-throw
        else
            throw new ECAException("Error creating lightweight CA certificate: " + e, e);
    }

    CertificateAuthority ca = new CertificateAuthority(hostCA, subjectX500Name, aid, this.authorityID,
            cert.getSerialNumber(), nickname, Collections.singleton(thisClone), description, true);

    // Update authority record with serial of issued cert
    LDAPModificationSet mods = new LDAPModificationSet();
    mods.add(LDAPModification.REPLACE, new LDAPAttribute("authoritySerial", cert.getSerialNumber().toString()));
    ca.modifyAuthorityEntry(mods);

    return ca;
}

From source file:org.ejbca.core.protocol.ws.client.CvcRequestCommand.java

/**
 * Runs the command//ww  w  .j  av a2s.  c  o  m
 *
 * @throws IllegalAdminCommandException Error in command args
 * @throws ErrorAdminCommandException Error running command
 */
public void execute() throws IllegalAdminCommandException, ErrorAdminCommandException {

    try {
        if (args.length < 9 || args.length > 11) {
            getPrintStream().println("Number of arguments: " + args.length);
            usage();
            System.exit(-1); // NOPMD, this is not a JEE app
        }

        String username = args[ARG_USERNAME];
        String userpassword = args[ARG_PASSWORD];
        String dn = args[ARG_SUBJECTDN];
        String sequence = args[ARG_SEQUENCE];
        String signatureAlg = args[ARG_SIGNALG];
        String keySpec = args[ARG_KEYSPEC];
        boolean genrequest = args[ARG_GENREQ].equalsIgnoreCase("true");
        String basefilename = args[ARG_BASEFILENAME];
        String authSignKeyFile = null;
        if (args.length > (ARG_AUTHSIGNKEY)) {
            authSignKeyFile = args[ARG_AUTHSIGNKEY];
        }
        String authSignCertFile = null;
        if (args.length > (ARG_AUTHSIGNCERT)) {
            authSignCertFile = args[ARG_AUTHSIGNCERT];
        }

        getPrintStream().println("Enrolling user:");
        getPrintStream().println("Username: " + username);
        getPrintStream().println("Subject name: " + dn);
        getPrintStream().println("Sequence: " + sequence);
        getPrintStream().println("Signature algorithm: " + signatureAlg);
        getPrintStream().println("Key spec: " + keySpec);

        try {
            CryptoProviderTools.installBCProvider();

            String cvcreq = null;
            if (genrequest) {
                getPrintStream().println("Generating a new request with base filename: " + basefilename);
                // Generate keys for the request
                String keytype = "RSA";
                if (signatureAlg.contains("ECDSA")) {
                    keytype = "ECDSA";
                }
                KeyPair keyPair = KeyTools.genKeys(keySpec, keytype);
                String country = CertTools.getPartFromDN(dn, "C");
                String mnemonic = CertTools.getPartFromDN(dn, "CN");
                if (sequence.equalsIgnoreCase("null")) {
                    sequence = RandomStringUtils.randomNumeric(5);
                    getPrintStream().println("No sequence given, using random 5 number sequence: " + sequence);
                }
                //CAReferenceField caRef = new CAReferenceField(country,mnemonic,sequence);
                CAReferenceField caRef = null; // Don't create a caRef in the self signed request
                // We are making a self signed request, so holder ref is same as ca ref
                HolderReferenceField holderRef = new HolderReferenceField(country, mnemonic, sequence);
                CVCertificate request = CertificateGenerator.createRequest(keyPair, signatureAlg, caRef,
                        holderRef);
                byte[] der = request.getDEREncoded();
                if (authSignKeyFile != null) {
                    getPrintStream().println("Reading private key from pkcs8 file " + authSignKeyFile
                            + " to create an authenticated request");
                    byte[] keybytes = FileTools.readFiletoBuffer(authSignKeyFile);
                    KeyFactory keyfact = KeyFactory.getInstance(keytype, "BC");
                    PrivateKey privKey = keyfact.generatePrivate(new PKCS8EncodedKeySpec(keybytes));
                    KeyPair authKeyPair = new KeyPair(null, privKey); // We don't need the public key
                    // Default caRef if we do not pass in a certificate to get caRef from
                    CAReferenceField authCaRef = new CAReferenceField(country, mnemonic, sequence);
                    CVCertificate authCert = null;
                    if (authSignCertFile != null) {
                        getPrintStream().println("Reading cert from cvcert file " + authSignCertFile
                                + " to create an authenticated request");
                        CVCObject parsedObject = CvcPrintCommand.getCVCObject(authSignCertFile);
                        authCert = (CVCertificate) parsedObject;
                        String c = authCert.getCertificateBody().getHolderReference().getCountry();
                        String m = authCert.getCertificateBody().getHolderReference().getMnemonic();
                        String s = authCert.getCertificateBody().getHolderReference().getSequence();
                        authCaRef = new CAReferenceField(c, m, s);
                    }
                    CVCAuthenticatedRequest authRequest = CertificateGenerator
                            .createAuthenticatedRequest(request, authKeyPair, signatureAlg, authCaRef);
                    // Test to verify it yourself first
                    if (authCert != null) {
                        getPrintStream().println("Verifying the request before sending it...");
                        PublicKey pk = KeyTools.getECPublicKeyWithParams(
                                authCert.getCertificateBody().getPublicKey(), keySpec);
                        authRequest.verify(pk);
                    }
                    der = authRequest.getDEREncoded();
                }
                cvcreq = new String(Base64.encode(der));
                // Print the generated request to file
                FileOutputStream fos = new FileOutputStream(basefilename + ".cvreq");
                fos.write(der);
                fos.close();
                getPrintStream().println("Wrote binary request to: " + basefilename + ".cvreq");
                fos = new FileOutputStream(basefilename + ".pkcs8");
                fos.write(keyPair.getPrivate().getEncoded());
                fos.close();
                getPrintStream().println("Wrote private key in " + keyPair.getPrivate().getFormat()
                        + " format to to: " + basefilename + ".pkcs8");
            } else {
                // Read request from file
                getPrintStream().println("Reading request from filename: " + basefilename + ".cvreq");
                byte[] der = FileTools.readFiletoBuffer(basefilename + ".cvreq");
                cvcreq = new String(Base64.encode(der));
            }

            // Edit a user, creating it if it does not exist
            // Actually don't do that, leverage the existing commands and force to use the editUser command instead.
            // This also makes this CLI exactly represent the actual WS-API call 
            // getEjbcaRAWS().editUser(userdata);

            getPrintStream().println("Submitting CVC request for user '" + username + "'.");
            getPrintStream().println();
            // Use the request and request a certificate
            List<Certificate> resp = getEjbcaRAWS().cvcRequest(username, userpassword, cvcreq);

            // Handle the response
            Certificate cert = resp.get(0);
            byte[] b64cert = cert.getCertificateData();
            CVCObject parsedObject = CertificateParser.parseCertificate(Base64.decode(b64cert));
            CVCertificate cvcert = (CVCertificate) parsedObject;
            FileOutputStream fos = new FileOutputStream(basefilename + ".cvcert");
            fos.write(cvcert.getDEREncoded());
            fos.close();
            getPrintStream().println("Wrote binary certificate to: " + basefilename + ".cvcert");
            getPrintStream().println("You can look at the certificate with the command cvcwscli.sh cvcprint "
                    + basefilename + ".cvcert");
        } catch (AuthorizationDeniedException_Exception e) {
            getPrintStream().println("Error : " + e.getMessage());
        } catch (UserDoesntFullfillEndEntityProfile_Exception e) {
            getPrintStream()
                    .println("Error : Given userdata doesn't fullfill end entity profile. : " + e.getMessage());
        }

    } catch (Exception e) {
        if (e instanceof EjbcaException_Exception) {
            EjbcaException_Exception e1 = (EjbcaException_Exception) e;
            getPrintStream()
                    .println("Error code is: " + e1.getFaultInfo().getErrorCode().getInternalErrorCode());
        }
        throw new ErrorAdminCommandException(e);
    }
}