Example usage for java.security PrivateKey getEncoded

List of usage examples for java.security PrivateKey getEncoded

Introduction

In this page you can find the example usage for java.security PrivateKey getEncoded.

Prototype

public byte[] getEncoded();

Source Link

Document

Returns the key in its primary encoding format, or null if this key does not support encoding.

Usage

From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java

/**
 * Returns a signed certificate.//  w  w  w.j ava  2 s  .c o m
 *
 * @param builder
 *            builder to create the certificate
 * @param key
 *            private key for the certificate
 * @return a signed certificate
 * @throws OperatorCreationException
 *             if there was a problem creation a bouncy castle operator
 * @throws CertificateException
 *             if any of the certificates in the keystore could not be
 *             loaded
 */
private final X509Certificate getSignedCertificate(final X509v3CertificateBuilder builder, final PrivateKey key)
        throws OperatorCreationException, CertificateException {
    final ContentSigner signer; // Content signer
    final String provider; // Provider
    final X509Certificate signed; // Signed certificate

    provider = BouncyCastleProvider.PROVIDER_NAME;
    signer = new JcaContentSignerBuilder(getSignatureAlgorithm()).setProvider(provider).build(key);

    signed = new JcaX509CertificateConverter().setProvider(provider).getCertificate(builder.build(signer));

    LOGGER.debug("Signed certificate with {} private key {}, using algorithm {}", key.getAlgorithm(),
            Arrays.asList(key.getEncoded()), key.getFormat());

    return signed;
}

From source file:org.cesecore.keys.token.BaseCryptoToken.java

/**
 * This method extracts a PrivateKey from the keystore and wraps it, using a symmetric encryption key
 *
 * @param privKeyTransform - transformation algorithm
 * @param spec - transformation algorithm spec (e.g: IvParameterSpec for CBC mode)
 * @param encryptionKeyAlias - alias of the symmetric key that will encrypt the private key
 * @param privateKeyAlias - alias for the PrivateKey to be extracted
 * @return byte[] with the encrypted extracted key
 * @throws NoSuchAlgorithmException if privKeyTransform is null, empty, in an invalid format, or if no Provider supports a CipherSpi
 *             implementation for the specified algorithm.
 * @throws NoSuchPaddingException if privKeyTransform contains a padding scheme that is not available.
 * @throws NoSuchProviderException if BouncyCastle is not registered in the security provider list.
 * @throws InvalidKeyException if the encryption key derived from encryptionKeyAlias was invalid.
 * @throws IllegalBlockSizeException if the Cipher created using privKeyTransform is a block cipher, no padding has been requested, and the length
 *             of the encoding of the key to be wrapped is not a multiple of the block size.
 * @throws CryptoTokenOfflineException if Crypto Token is not available or connected, or key with alias does not exist.
 * @throws InvalidAlgorithmParameterException if spec id not valid or supported.
 * @throws PrivateKeyNotExtractableException if the key is not extractable, does not exist or encryption fails
 *///from  ww  w.j a va2 s  .  co  m
public byte[] extractKey(String privKeyTransform, AlgorithmParameterSpec spec, String encryptionKeyAlias,
        String privateKeyAlias) throws NoSuchAlgorithmException, NoSuchPaddingException,
        NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, CryptoTokenOfflineException,
        PrivateKeyNotExtractableException, InvalidAlgorithmParameterException {

    if (doPermitExtractablePrivateKey()) {
        // get encryption key
        Key encryptionKey = getKey(encryptionKeyAlias);
        // get private key to wrap
        PrivateKey privateKey = getPrivateKey(privateKeyAlias);
        if (privateKey == null) {
            throw new PrivateKeyNotExtractableException(
                    "Extracting key with alias '" + privateKeyAlias + "' return null.");
        }

        // since SUN PKCS11 Provider does not implements WRAP_MODE,
        // ENCRYPT_MODE with encoded private key will be used instead, giving the same result
        Cipher c = null;
        c = Cipher.getInstance(privKeyTransform, getEncProviderName());
        if (spec == null) {
            c.init(Cipher.ENCRYPT_MODE, encryptionKey);
        } else {
            c.init(Cipher.ENCRYPT_MODE, encryptionKey, spec);
        }

        // wrap key
        byte[] encryptedKey;
        try {
            byte[] data = privateKey.getEncoded();
            if (StringUtils.containsIgnoreCase(privKeyTransform, "NoPadding")) {
                // We must add PKCS7/PKCS5 padding ourselves to the data
                final PKCS7Padding padding = new PKCS7Padding();
                // Calculate the number of pad bytes needed
                final int rem = data.length % c.getBlockSize();
                final int padlen = c.getBlockSize() - rem;
                if (log.isDebugEnabled()) {
                    log.debug("Padding key data with " + padlen + " bytes, using PKCS7/5Padding. Total len: "
                            + (data.length + padlen));
                }
                byte[] newdata = Arrays.copyOf(data, data.length + padlen);
                padding.addPadding(newdata, data.length);
                data = newdata;
            }
            encryptedKey = c.doFinal(data);
        } catch (BadPaddingException e) {
            throw new PrivateKeyNotExtractableException(
                    "Extracting key with alias '" + privateKeyAlias + "' failed.");
        }

        return encryptedKey;
    } else {
        final String msg = intres.getLocalizedMessage("token.errornotextractable", privateKeyAlias,
                encryptionKeyAlias);
        throw new PrivateKeyNotExtractableException(msg);
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

private void generateAndStorePersonalInfo(SQLiteDatabase db) {
    String email = getUserEmail();
    String name = email; // How to get this?

    KeyPair keypair = DBIdentityProvider.generateKeyPair();
    PrivateKey privateKey = keypair.getPrivate();
    PublicKey publicKey = keypair.getPublic();
    String pubKeyStr = FastBase64.encodeToString(publicKey.getEncoded());
    String privKeyStr = FastBase64.encodeToString(privateKey.getEncoded());
    ContentValues cv = new ContentValues();
    cv.put(MyInfo.PUBLIC_KEY, pubKeyStr);
    cv.put(MyInfo.PRIVATE_KEY, privKeyStr);
    cv.put(MyInfo.NAME, name);//from  w w  w .j  a v a  2  s .c  o  m
    cv.put(MyInfo.EMAIL, email);
    db.insertOrThrow(MyInfo.TABLE, null, cv);
    Log.d(TAG, "Generated public key: " + pubKeyStr);
    Log.d(TAG, "Generated priv key: **************");
}

From source file:org.ejbca.util.keystore.KeyTools.java

/**
 * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is
 * set to 'privateKey' and the private key password is null.
 *
 * @param alias the alias used for the key entry
 * @param privKey RSA private key//from   www  .j a va 2s.c  o m
 * @param cert user certificate
 * @param cachain CA-certificate chain or null if only one cert in chain, in that case use 'cert'.
 * @return KeyStore containing PKCS12-keystore
 * @exception Exception if input parameters are not OK or certificate generation fails
 */
public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert,
        final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    if (log.isTraceEnabled()) {
        log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    // Certificate chain
    if (cert == null) {
        throw new IllegalArgumentException("Parameter cert cannot be null.");
    }
    int len = 1;
    if (cachain != null) {
        len += cachain.length;
    }
    final Certificate[] chain = new Certificate[len];
    // To not get a ClassCastException we need to generate a real new certificate with BC
    final CertificateFactory cf = CertTools.getCertificateFactory();
    chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));

    if (cachain != null) {
        for (int i = 0; i < cachain.length; i++) {
            final X509Certificate tmpcert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded()));
            chain[i + 1] = tmpcert;
        }
    }
    if (chain.length > 1) {
        for (int i = 1; i < chain.length; i++) {
            final X509Certificate cacert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded()));
            // Set attributes on CA-cert
            try {
                final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i];
                // We construct a friendly name for the CA, and try with some parts from the DN if they exist.
                String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN");
                // On the ones below we +i to make it unique, O might not be otherwise
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O") + i;
                }
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU" + i);
                }
                if (cafriendly == null) {
                    cafriendly = "CA_unknown" + i;
                }
                caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                        new DERBMPString(cafriendly));
            } catch (ClassCastException e) {
                log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
            }
        }
    }

    // Set attributes on user-cert
    try {
        final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0];
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        // in this case we just set the local key id to that of the public key
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // "Clean" private key, i.e. remove any old attributes
    final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC");
    final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded()));
    // Set attributes for private key
    try {
        final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk;
        // in this case we just set the local key id to that of the public key
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // store the key and the certificate chain
    final KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    store.load(null, null);
    store.setKeyEntry(alias, pk, null, chain);
    if (log.isTraceEnabled()) {
        log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    return store;
}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

@Override
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public byte[] exportCAKeyStore(AuthenticationToken admin, String caname, String keystorepass,
        String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) {
    log.trace(">exportCAKeyStore");
    try {/*from w ww  .  j  a  va 2  s .co  m*/
        final CA thisCa = caSession.getCAForEdit(admin, caname);
        // Make sure we are not trying to export a hard or invalid token
        CAToken thisCAToken = thisCa.getCAToken();
        final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(thisCAToken.getCryptoTokenId());
        if (!(cryptoToken instanceof SoftCryptoToken)) {
            throw new IllegalCryptoTokenException("Cannot export anything but a soft token.");
        }
        // Do not allow export without password protection
        if (StringUtils.isEmpty(keystorepass) || StringUtils.isEmpty(privkeypass)) {
            throw new IllegalArgumentException("Cannot export a token without password protection.");
        }
        // Check authorization
        if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) {
            String msg = intres.getLocalizedMessage("caadmin.notauthorizedtoexportcatoken", caname);
            Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    admin.toString(), String.valueOf(thisCa.getCAId()), null, null, details);
            throw new AuthorizationDeniedException(msg);
        }
        // Fetch keys
        final char[] password = keystorepass.toCharArray();
        ((SoftCryptoToken) cryptoToken).checkPasswordBeforeExport(password);
        cryptoToken.activate(password);

        PrivateKey p12PrivateEncryptionKey = cryptoToken
                .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT));
        PublicKey p12PublicEncryptionKey = cryptoToken
                .getPublicKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT));
        PrivateKey p12PrivateCertSignKey = cryptoToken
                .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));
        PrivateKey p12PrivateCRLSignKey = cryptoToken
                .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN));
        if (!p12PrivateCertSignKey.equals(p12PrivateCRLSignKey)) {
            throw new Exception("Assertion of equal signature keys failed.");
        }
        // Proceed with the export
        byte[] ret = null;
        String format = null;
        if (thisCa.getCAType() == CAInfo.CATYPE_CVC) {
            log.debug("Exporting private key with algorithm: " + p12PrivateCertSignKey.getAlgorithm()
                    + " of format: " + p12PrivateCertSignKey.getFormat());
            format = p12PrivateCertSignKey.getFormat();
            ret = p12PrivateCertSignKey.getEncoded();
        } else {
            log.debug("Exporting PKCS12 keystore");
            format = "PKCS12";
            KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
            keystore.load(null, keystorepass.toCharArray());
            // Load keys into keystore
            Certificate[] certificateChainSignature = (Certificate[]) thisCa.getCertificateChain()
                    .toArray(new Certificate[0]);
            Certificate[] certificateChainEncryption = new Certificate[1];
            // certificateChainSignature[0].getSigAlgName(),
            // generate dummy certificate for encryption key.
            certificateChainEncryption[0] = CertTools.genSelfCertForPurpose("CN=dummy2", 36500, null,
                    p12PrivateEncryptionKey, p12PublicEncryptionKey, thisCAToken.getEncryptionAlgorithm(), true,
                    X509KeyUsage.keyEncipherment, true);
            log.debug("Exporting with sigAlgorithm "
                    + AlgorithmTools.getSignatureAlgorithm(certificateChainSignature[0]) + "encAlgorithm="
                    + thisCAToken.getEncryptionAlgorithm());
            if (keystore.isKeyEntry(privateSignatureKeyAlias)) {
                throw new Exception("Key \"" + privateSignatureKeyAlias + "\"already exists in keystore.");
            }
            if (keystore.isKeyEntry(privateEncryptionKeyAlias)) {
                throw new Exception("Key \"" + privateEncryptionKeyAlias + "\"already exists in keystore.");
            }

            keystore.setKeyEntry(privateSignatureKeyAlias, p12PrivateCertSignKey, privkeypass.toCharArray(),
                    certificateChainSignature);
            keystore.setKeyEntry(privateEncryptionKeyAlias, p12PrivateEncryptionKey, privkeypass.toCharArray(),
                    certificateChainEncryption);
            // Return KeyStore as byte array and clean up
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            keystore.store(baos, keystorepass.toCharArray());
            if (keystore.isKeyEntry(privateSignatureKeyAlias)) {
                keystore.deleteEntry(privateSignatureKeyAlias);
            }
            if (keystore.isKeyEntry(privateEncryptionKeyAlias)) {
                keystore.deleteEntry(privateEncryptionKeyAlias);
            }
            ret = baos.toByteArray();
        }
        String msg = intres.getLocalizedMessage("caadmin.exportedca", caname, format);
        Map<String, Object> details = new LinkedHashMap<String, Object>();
        details.put("msg", msg);
        auditSession.log(EjbcaEventTypes.CA_EXPORTTOKEN, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), String.valueOf(thisCa.getCAId()), null, null, details);
        log.trace("<exportCAKeyStore");
        return ret;
    } catch (Exception e) {
        String msg = intres.getLocalizedMessage("caadmin.errorexportca", caname, "PKCS12", e.getMessage());
        Map<String, Object> details = new LinkedHashMap<String, Object>();
        details.put("msg", msg);
        auditSession.log(EjbcaEventTypes.CA_EXPORTTOKEN, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), null, null, null, details);
        throw new EJBException(e);
    }
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is set to 'privateKey' and the private key password is
 * null.// w  w  w. j a v a  2  s  . com
 * 
 * @param alias
 *            the alias used for the key entry
 * @param privKey
 *            RSA private key
 * @param cert
 *            user certificate
 * @param cachain
 *            CA-certificate chain or null if only one cert in chain, in that case use 'cert'.
 * @return KeyStore containing PKCS12-keystore
 * @exception Exception
 *                if input parameters are not OK or certificate generation fails
 */
public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert,
        final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    if (log.isTraceEnabled()) {
        log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    // Certificate chain
    if (cert == null) {
        throw new IllegalArgumentException("Parameter cert cannot be null.");
    }
    int len = 1;
    if (cachain != null) {
        len += cachain.length;
    }
    final Certificate[] chain = new Certificate[len];
    // To not get a ClassCastException we need to generate a real new certificate with BC
    final CertificateFactory cf = CertTools.getCertificateFactory();
    chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));

    if (cachain != null) {
        for (int i = 0; i < cachain.length; i++) {
            final X509Certificate tmpcert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded()));
            chain[i + 1] = tmpcert;
        }
    }
    if (chain.length > 1) {
        for (int i = 1; i < chain.length; i++) {
            final X509Certificate cacert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded()));
            // Set attributes on CA-cert
            try {
                final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i];
                // We construct a friendly name for the CA, and try with some parts from the DN if they exist.
                String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN");
                // On the ones below we +i to make it unique, O might not be otherwise
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O");
                    if (cafriendly == null) {
                        cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU");
                        if (cafriendly == null) {
                            cafriendly = "CA_unknown" + i;
                        } else {
                            cafriendly = cafriendly + i;
                        }
                    } else {
                        cafriendly = cafriendly + i;
                    }
                }
                caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                        new DERBMPString(cafriendly));
            } catch (ClassCastException e) {
                log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
            }
        }
    }

    // Set attributes on user-cert
    try {
        final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0];
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        // in this case we just set the local key id to that of the public key
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // "Clean" private key, i.e. remove any old attributes
    final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC");
    final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded()));
    // Set attributes for private key
    try {
        final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk;
        // in this case we just set the local key id to that of the public key
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // store the key and the certificate chain
    final KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    store.load(null, null);
    store.setKeyEntry(alias, pk, null, chain);
    if (log.isTraceEnabled()) {
        log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    return store;
}

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

protected void keyRecoverAny() throws Exception {
    log.trace(">keyRecoverAny");
    GlobalConfiguration gc = (GlobalConfiguration) globalConfigurationSession
            .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID);
    boolean krenabled = gc.getEnableKeyRecovery();
    if (!krenabled == true) {
        gc.setEnableKeyRecovery(true);/*from   w  ww.j a  va  2  s  .c  om*/
        globalConfigurationSession.saveConfiguration(intAdmin, gc);
    }

    // Add a new user, set token to P12, status to new and end entity
    // profile to key recovery
    UserDataVOWS user1 = new UserDataVOWS();
    user1.setKeyRecoverable(true);
    user1.setUsername("WSTESTUSERKEYREC2");
    user1.setPassword("foo456");
    user1.setClearPwd(true);
    user1.setSubjectDN("CN=WSTESTUSERKEYREC2");
    user1.setCaName(getAdminCAName());
    user1.setEmail(null);
    user1.setSubjectAltName(null);
    user1.setStatus(UserDataVOWS.STATUS_NEW);
    user1.setTokenType(UserDataVOWS.TOKEN_TYPE_P12);
    user1.setEndEntityProfileName("KEYRECOVERY");
    user1.setCertificateProfileName("ENDUSER");
    ejbcaraws.editUser(user1);

    UserMatch usermatch = new UserMatch();
    usermatch.setMatchwith(UserMatch.MATCH_WITH_USERNAME);
    usermatch.setMatchtype(UserMatch.MATCH_TYPE_EQUALS);
    usermatch.setMatchvalue("WSTESTUSERKEYREC2");

    List<java.security.KeyStore> keyStores = new ArrayList<java.security.KeyStore>();

    // generate 4 certificates
    for (int i = 0; i < 4; i++) {
        List<UserDataVOWS> userdatas = ejbcaraws.findUser(usermatch);
        assertTrue(userdatas != null);
        assertTrue(userdatas.size() == 1);
        user1 = userdatas.get(0);
        // Surely not all of these properties need to be set again?
        user1.setKeyRecoverable(true);
        user1.setUsername("WSTESTUSERKEYREC2");
        user1.setPassword("foo456");
        user1.setClearPwd(true);
        user1.setSubjectDN("CN=WSTESTUSERKEYREC2");
        user1.setCaName(getAdminCAName());
        user1.setEmail(null);
        user1.setSubjectAltName(null);
        user1.setStatus(UserDataVOWS.STATUS_NEW);
        user1.setTokenType(UserDataVOWS.TOKEN_TYPE_P12);
        user1.setEndEntityProfileName("KEYRECOVERY");
        user1.setCertificateProfileName("ENDUSER");
        ejbcaraws.editUser(user1);

        KeyStore ksenv = ejbcaraws.pkcs12Req("WSTESTUSERKEYREC2", "foo456", null, "1024",
                AlgorithmConstants.KEYALGORITHM_RSA);
        java.security.KeyStore ks = KeyStoreHelper.getKeyStore(ksenv.getKeystoreData(), "PKCS12", "foo456");
        assertNotNull(ks);
        keyStores.add(ks);
    }

    // user should have 4 certificates
    assertTrue(keyStores.size() == 4);

    // recover all keys
    for (java.security.KeyStore ks : keyStores) {
        Enumeration<String> en = ks.aliases();
        String alias = (String) en.nextElement();
        // You never know in which order the certificates in the KS are returned, it's different between java 6 and 7 for ex 
        if (!ks.isKeyEntry(alias)) {
            alias = (String) en.nextElement();
        }
        X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
        assertEquals(cert.getSubjectDN().toString(), "CN=WSTESTUSERKEYREC2");
        PrivateKey privK = (PrivateKey) ks.getKey(alias, "foo456".toCharArray());
        log.info("recovering key. sn " + cert.getSerialNumber().toString(16) + " issuer "
                + cert.getIssuerDN().toString());

        // recover key
        ejbcaraws.keyRecover("WSTESTUSERKEYREC2", cert.getSerialNumber().toString(16),
                cert.getIssuerDN().toString());

        // A new PK12 request now should return the same key and certificate
        KeyStore ksenv = ejbcaraws.pkcs12Req("WSTESTUSERKEYREC2", "foo456", null, "1024",
                AlgorithmConstants.KEYALGORITHM_RSA);
        java.security.KeyStore ks2 = KeyStoreHelper.getKeyStore(ksenv.getKeystoreData(), "PKCS12", "foo456");
        assertNotNull(ks2);
        en = ks2.aliases();
        alias = (String) en.nextElement();
        // You never know in which order the certificates in the KS are returned, it's different between java 6 and 7 for ex 
        if (!ks.isKeyEntry(alias)) {
            alias = (String) en.nextElement();
        }
        X509Certificate cert2 = (X509Certificate) ks2.getCertificate(alias);
        assertEquals(cert2.getSubjectDN().toString(), "CN=WSTESTUSERKEYREC2");
        PrivateKey privK2 = (PrivateKey) ks2.getKey(alias, "foo456".toCharArray());

        // Compare certificates
        assertEquals(cert.getSerialNumber().toString(16), cert2.getSerialNumber().toString(16));
        // Compare keys
        String key1 = new String(Hex.encode(privK.getEncoded()));
        String key2 = new String(Hex.encode(privK2.getEncoded()));
        assertEquals(key1, key2);

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

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

protected void keyRecover() throws Exception {
    log.trace(">keyRecover");
    GlobalConfiguration gc = (GlobalConfiguration) globalConfigurationSession
            .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID);
    boolean krenabled = gc.getEnableKeyRecovery();
    if (krenabled == true) {
        gc.setEnableKeyRecovery(false);//from w  w  w . j av  a  2  s .c om
        globalConfigurationSession.saveConfiguration(intAdmin, gc);
    }

    boolean trows = false;
    try {
        // This should throw an exception that key recovery is not enabled
        ejbcaraws.keyRecoverNewest(CA1_WSTESTUSER1);
    } catch (EjbcaException_Exception e) {
        trows = true;
        // e.printStackTrace();
        assertEquals(e.getMessage(),
                "Keyrecovery have to be enabled in the system configuration in order to use this command.");
    }
    assertTrue(trows);

    // Set key recovery enabled
    gc.setEnableKeyRecovery(true);
    globalConfigurationSession.saveConfiguration(intAdmin, gc);

    trows = false;
    try {
        // This should throw an exception that the user does not exist
        ejbcaraws.keyRecoverNewest("sdfjhdiuwerw43768754###");
    } catch (NotFoundException_Exception e) {
        trows = true;
        // e.printStackTrace();
        assertEquals(e.getMessage(), "Wrong username or password");
    }
    assertTrue(trows);

    // Add a new End entity profile, KEYRECOVERY
    EndEntityProfile profile = new EndEntityProfile();
    profile.addField(DnComponents.COMMONNAME);
    profile.setUse(EndEntityProfile.KEYRECOVERABLE, 0, true);
    profile.setValue(EndEntityProfile.KEYRECOVERABLE, 0, EndEntityProfile.TRUE);
    profile.setUse(EndEntityProfile.KEYRECOVERABLE, 0, true);
    profile.setUse(EndEntityProfile.CLEARTEXTPASSWORD, 0, true);
    profile.setReUseKeyRecoveredCertificate(true);
    profile.setValue(EndEntityProfile.AVAILCAS, 0, Integer.toString(SecConst.ALLCAS));
    endEntityProfileSession.addEndEntityProfile(intAdmin, "KEYRECOVERY", profile);
    assertTrue("Unable to create KEYRECOVERY end entity profile.",
            endEntityProfileSession.getEndEntityProfile("KEYRECOVERY") != null);

    // Add a new user, set token to P12, status to new and end entity
    // profile to key recovery
    UserDataVOWS user1 = new UserDataVOWS();
    user1.setKeyRecoverable(true);
    user1.setUsername("WSTESTUSERKEYREC1");
    user1.setPassword("foo456");
    user1.setClearPwd(true);
    user1.setSubjectDN("CN=WSTESTUSERKEYREC1");
    user1.setCaName(getAdminCAName());
    user1.setEmail(null);
    user1.setSubjectAltName(null);
    user1.setStatus(UserDataVOWS.STATUS_NEW);
    user1.setTokenType(UserDataVOWS.TOKEN_TYPE_P12);
    user1.setEndEntityProfileName("KEYRECOVERY");
    user1.setCertificateProfileName("ENDUSER");
    ejbcaraws.editUser(user1);

    KeyStore ksenv = ejbcaraws.pkcs12Req("WSTESTUSERKEYREC1", "foo456", null, "1024",
            AlgorithmConstants.KEYALGORITHM_RSA);
    java.security.KeyStore ks = KeyStoreHelper.getKeyStore(ksenv.getKeystoreData(), "PKCS12", "foo456");
    assertNotNull(ks);
    Enumeration<String> en = ks.aliases();
    String alias = en.nextElement();
    if (!ks.isKeyEntry(alias)) {
        alias = en.nextElement();
    }
    X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
    assertEquals("CN=WSTESTUSERKEYREC1", cert.getSubjectDN().toString());
    PrivateKey privK = (PrivateKey) ks.getKey(alias, "foo456".toCharArray());

    // This should work now
    ejbcaraws.keyRecoverNewest("WSTESTUSERKEYREC1");

    // Set status to keyrecovery
    UserMatch usermatch = new UserMatch();
    usermatch.setMatchwith(UserMatch.MATCH_WITH_USERNAME);
    usermatch.setMatchtype(UserMatch.MATCH_TYPE_EQUALS);
    usermatch.setMatchvalue("WSTESTUSERKEYREC1");
    List<UserDataVOWS> userdatas = ejbcaraws.findUser(usermatch);
    assertTrue(userdatas != null);
    assertTrue(userdatas.size() == 1);
    userdatas.get(0).setStatus(EndEntityConstants.STATUS_KEYRECOVERY);
    ejbcaraws.editUser(userdatas.get(0));
    // A new PK12 request now should return the same key and certificate
    KeyStore ksenv2 = ejbcaraws.pkcs12Req("WSTESTUSERKEYREC1", "foo456", null, "1024",
            AlgorithmConstants.KEYALGORITHM_RSA);
    java.security.KeyStore ks2 = KeyStoreHelper.getKeyStore(ksenv2.getKeystoreData(), "PKCS12", "foo456");
    assertNotNull(ks2);
    en = ks2.aliases();
    alias = (String) en.nextElement();
    // You never know in which order the certificates in the KS are returned, it's different between java 6 and 7 for ex 
    if (!ks2.isKeyEntry(alias)) {
        alias = (String) en.nextElement();
    }
    X509Certificate cert2 = (X509Certificate) ks2.getCertificate(alias);
    assertEquals(cert2.getSubjectDN().toString(), "CN=WSTESTUSERKEYREC1");
    PrivateKey privK2 = (PrivateKey) ks2.getKey(alias, "foo456".toCharArray());

    // Compare certificates
    assertEquals(cert.getSerialNumber().toString(16), cert2.getSerialNumber().toString(16));
    // Compare keys
    String key1 = new String(Hex.encode(privK.getEncoded()));
    String key2 = new String(Hex.encode(privK2.getEncoded()));
    assertEquals(key1, key2);
    log.trace("<keyRecover");
}

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

protected void generatePkcs12() throws Exception {
    log.trace(">generatePkcs12");
    boolean exceptionThrown = false;
    try {/*  w w  w .  ja  v a  2 s .  c o m*/
        ejbcaraws.pkcs12Req(CA1_WSTESTUSER1, PASSWORD, null, "1024", AlgorithmConstants.KEYALGORITHM_RSA);
    } catch (EjbcaException_Exception e) {
        exceptionThrown = true;
    }
    assertTrue(exceptionThrown);// Should fail

    // Change token to P12
    UserMatch usermatch = new UserMatch();
    usermatch.setMatchwith(UserMatch.MATCH_WITH_USERNAME);
    usermatch.setMatchtype(UserMatch.MATCH_TYPE_EQUALS);
    usermatch.setMatchvalue(CA1_WSTESTUSER1);
    List<UserDataVOWS> userdatas = ejbcaraws.findUser(usermatch);
    assertNotNull(userdatas);
    assertEquals(1, userdatas.size());
    userdatas.get(0).setTokenType(UserDataVOWS.TOKEN_TYPE_P12);
    userdatas.get(0).setSubjectDN(getDN(CA1_WSTESTUSER1));
    ejbcaraws.editUser(userdatas.get(0));

    exceptionThrown = false;
    try {
        ejbcaraws.pkcs12Req(CA1_WSTESTUSER1, PASSWORD, null, "1024", AlgorithmConstants.KEYALGORITHM_RSA);
    } catch (EjbcaException_Exception e) {
        exceptionThrown = true;
    }
    assertTrue(exceptionThrown); // Should fail

    // Change password to foo456 and status to NEW
    userdatas.get(0).setStatus(UserDataVOWS.STATUS_NEW);
    userdatas.get(0).setPassword("foo456");
    userdatas.get(0).setClearPwd(true);
    ejbcaraws.editUser(userdatas.get(0));

    KeyStore ksenv = null;
    try {
        ksenv = ejbcaraws.pkcs12Req(CA1_WSTESTUSER1, "foo456", null, "1024",
                AlgorithmConstants.KEYALGORITHM_RSA);
    } catch (EjbcaException_Exception e) {
        assertTrue(e.getMessage(), false);
    }

    assertNotNull(ksenv);

    java.security.KeyStore ks = KeyStoreHelper.getKeyStore(ksenv.getKeystoreData(), "PKCS12", "foo456");

    assertNotNull(ks);
    Enumeration<String> en = ks.aliases();
    String alias = en.nextElement();
    X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
    assertEquals(cert.getSubjectDN().toString(), getDN(CA1_WSTESTUSER1));
    PrivateKey privK1 = (PrivateKey) ks.getKey(alias, "foo456".toCharArray());
    log.info("test04GeneratePkcs12() Certificate " + cert.getSubjectDN().toString() + " equals "
            + getDN(CA1_WSTESTUSER1));

    // Generate a new one and make sure it is a new one and that key
    // recovery does not kick in by mistake
    // Set status to new
    usermatch = new UserMatch();
    usermatch.setMatchwith(UserMatch.MATCH_WITH_USERNAME);
    usermatch.setMatchtype(UserMatch.MATCH_TYPE_EQUALS);
    usermatch.setMatchvalue(CA1_WSTESTUSER1);
    userdatas = ejbcaraws.findUser(usermatch);
    assertTrue(userdatas != null);
    assertTrue(userdatas.size() == 1);
    userdatas.get(0).setStatus(UserDataVOWS.STATUS_NEW);
    userdatas.get(0).setPassword("foo456");
    userdatas.get(0).setClearPwd(true);
    ejbcaraws.editUser(userdatas.get(0));
    // A new PK12 request now should return the same key and certificate
    KeyStore ksenv2 = ejbcaraws.pkcs12Req(CA1_WSTESTUSER1, "foo456", null, "1024",
            AlgorithmConstants.KEYALGORITHM_RSA);
    java.security.KeyStore ks2 = KeyStoreHelper.getKeyStore(ksenv2.getKeystoreData(), "PKCS12", "foo456");
    assertNotNull(ks2);
    en = ks2.aliases();
    alias = (String) en.nextElement();
    X509Certificate cert2 = (X509Certificate) ks2.getCertificate(alias);
    assertEquals(cert2.getSubjectDN().toString(), getDN(CA1_WSTESTUSER1));
    PrivateKey privK2 = (PrivateKey) ks2.getKey(alias, "foo456".toCharArray());

    // Compare certificates, must not be the same
    assertFalse(cert.getSerialNumber().toString(16).equals(cert2.getSerialNumber().toString(16)));
    // Compare keys, must not be the same
    String key1 = new String(Hex.encode(privK1.getEncoded()));
    String key2 = new String(Hex.encode(privK2.getEncoded()));
    assertFalse(key1.equals(key2));

    // Test the method for adding/editing and requesting a PKCS#12 KeyStore
    // in a single transaction
    ksenv2 = ejbcaraws.softTokenRequest(userdatas.get(0), null, "1024", AlgorithmConstants.KEYALGORITHM_RSA);
    ks2 = KeyStoreHelper.getKeyStore(ksenv2.getKeystoreData(), "PKCS12", "foo456");
    assertNotNull(ks2);
    en = ks2.aliases();
    alias = (String) en.nextElement();
    cert2 = (X509Certificate) ks2.getCertificate(alias);
    assertEquals(cert2.getSubjectDN().toString(), getDN(CA1_WSTESTUSER1));
    privK2 = (PrivateKey) ks2.getKey(alias, "foo456".toCharArray());

    // Test the method for adding/editing and requesting a JKS KeyStore in a
    // single transaction
    userdatas.get(0).setTokenType(UserDataVOWS.TOKEN_TYPE_JKS);
    ksenv2 = ejbcaraws.softTokenRequest(userdatas.get(0), null, "1024", AlgorithmConstants.KEYALGORITHM_RSA);
    ks2 = KeyStoreHelper.getKeyStore(ksenv2.getKeystoreData(), "JKS", "foo456");
    assertNotNull(ks2);
    en = ks2.aliases();
    alias = (String) en.nextElement();
    cert2 = (X509Certificate) ks2.getCertificate(alias);
    assertEquals(cert2.getSubjectX500Principal().getName(), getReversedDN(CA1_WSTESTUSER1));
    privK2 = (PrivateKey) ks2.getKey(alias, "foo456".toCharArray());
    log.trace("<generatePkcs12");
}