Example usage for java.security KeyStore isKeyEntry

List of usage examples for java.security KeyStore isKeyEntry

Introduction

In this page you can find the example usage for java.security KeyStore isKeyEntry.

Prototype

public final boolean isKeyEntry(String alias) throws KeyStoreException 

Source Link

Document

Returns true if the entry identified by the given alias was created by a call to setKeyEntry , or created by a call to setEntry with a PrivateKeyEntry or a SecretKeyEntry .

Usage

From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java

/**
 * This method will list 1. Certificate aliases 2. Private key alise 3. Private key value to a
 * given keystore./*from ww w.  jav a2  s. co  m*/
 *
 * @param keyStoreName The name of the keystore
 * @return Instance of KeyStoreData
 * @throws SecurityConfigException will be thrown
 */
public KeyStoreData getKeystoreInfo(String keyStoreName) throws SecurityConfigException {
    try {

        if (keyStoreName == null) {
            throw new Exception("keystore name cannot be null");
        }

        KeyStore keyStore;
        String keyStoreType;
        String privateKeyPassowrd = null;
        if (KeyStoreUtil.isPrimaryStore(keyStoreName)) {
            KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
            keyStore = keyMan.getPrimaryKeyStore();
            ServerConfiguration serverConfig = ServerConfiguration.getInstance();
            keyStoreType = serverConfig
                    .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_TYPE);
            privateKeyPassowrd = serverConfig
                    .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD);
        } else {
            String path = SecurityConstants.KEY_STORES + "/" + keyStoreName;
            if (!registry.resourceExists(path)) {
                throw new SecurityConfigException("Key Store not found");
            }
            Resource resource = registry.get(path);
            KeyStoreManager manager = KeyStoreManager.getInstance(tenantId);
            keyStore = manager.getKeyStore(keyStoreName);
            keyStoreType = resource.getProperty(SecurityConstants.PROP_TYPE);

            String encpass = resource.getProperty(SecurityConstants.PROP_PRIVATE_KEY_PASS);
            if (encpass != null) {
                CryptoUtil util = CryptoUtil.getDefaultCryptoUtil();
                privateKeyPassowrd = new String(util.base64DecodeAndDecrypt(encpass));
            }
        }
        // Fill the information about the certificates
        Enumeration<String> aliases = keyStore.aliases();
        List<org.wso2.carbon.security.keystore.service.CertData> certDataList = new ArrayList<>();
        Format formatter = new SimpleDateFormat("dd/MM/yyyy");

        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            if (keyStore.isCertificateEntry(alias)) {
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
                certDataList.add(fillCertData(cert, alias, formatter));
            }
        }

        // Create a cert array
        CertData[] certs = certDataList.toArray(new CertData[certDataList.size()]);

        // Create a KeyStoreData bean, set the name and fill in the cert information
        KeyStoreData keyStoreData = new KeyStoreData();
        keyStoreData.setKeyStoreName(keyStoreName);
        keyStoreData.setCerts(certs);
        keyStoreData.setKeyStoreType(keyStoreType);

        aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            // There be only one entry in WSAS related keystores
            if (keyStore.isKeyEntry(alias)) {
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
                keyStoreData.setKey(fillCertData(cert, alias, formatter));

                PrivateKey key = (PrivateKey) keyStore.getKey(alias, privateKeyPassowrd.toCharArray());
                String pemKey;
                pemKey = "-----BEGIN PRIVATE KEY-----\n";
                pemKey += Base64.encode(key.getEncoded());
                pemKey += "\n-----END PRIVATE KEY-----";
                keyStoreData.setKeyValue(pemKey);
                break;

            }
        }
        return keyStoreData;
    } catch (Exception e) {
        String msg = "Error has encounted while loading the keystore to the given keystore name "
                + keyStoreName;
        log.error(msg, e);
        throw new SecurityConfigException(msg);
    }

}

From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java

/**
 * This method will list 1. Certificate aliases 2. Private key alise 3. Private key value to a
 * given keystore.//ww w.  j a v  a  2s.  c  o m
 *
 * @param keyStoreName The name of the keystore
 * @param pageNumber   page number
 * @return Instance of KeyStoreData
 * @throws SecurityConfigException will be thrown
 */
public PaginatedKeyStoreData getPaginatedKeystoreInfo(String keyStoreName, int pageNumber)
        throws SecurityConfigException {
    try {

        if (keyStoreName == null) {
            throw new Exception("keystore name cannot be null");
        }

        KeyStore keyStore;
        String keyStoreType;
        String privateKeyPassowrd = null;
        if (KeyStoreUtil.isPrimaryStore(keyStoreName)) {
            KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
            keyStore = keyMan.getPrimaryKeyStore();
            ServerConfiguration serverConfig = ServerConfiguration.getInstance();
            keyStoreType = serverConfig
                    .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_TYPE);
            privateKeyPassowrd = serverConfig
                    .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD);
        } else {
            String path = SecurityConstants.KEY_STORES + "/" + keyStoreName;
            if (!registry.resourceExists(path)) {
                throw new SecurityConfigException("Key Store not found");
            }
            Resource resource = registry.get(path);
            KeyStoreManager manager = KeyStoreManager.getInstance(tenantId);
            keyStore = manager.getKeyStore(keyStoreName);
            keyStoreType = resource.getProperty(SecurityConstants.PROP_TYPE);

            String encpass = resource.getProperty(SecurityConstants.PROP_PRIVATE_KEY_PASS);
            if (encpass != null) {
                CryptoUtil util = CryptoUtil.getDefaultCryptoUtil();
                privateKeyPassowrd = new String(util.base64DecodeAndDecrypt(encpass));
            }
        }
        // Fill the information about the certificates
        Enumeration<String> aliases = keyStore.aliases();
        List<org.wso2.carbon.security.keystore.service.CertData> certDataList = new ArrayList<>();
        Format formatter = new SimpleDateFormat("dd/MM/yyyy");

        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            if (keyStore.isCertificateEntry(alias)) {
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
                certDataList.add(fillCertData(cert, alias, formatter));
            }
        }

        // Create a cert array
        CertData[] certs = certDataList.toArray(new CertData[certDataList.size()]);

        // Create a KeyStoreData bean, set the name and fill in the cert information
        PaginatedKeyStoreData keyStoreData = new PaginatedKeyStoreData();
        keyStoreData.setKeyStoreName(keyStoreName);
        keyStoreData.setPaginatedCertData(doPaging(pageNumber, certs));
        keyStoreData.setKeyStoreType(keyStoreType);

        aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            // There be only one entry in WSAS related keystores
            if (keyStore.isKeyEntry(alias)) {
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
                keyStoreData.setKey(fillCertData(cert, alias, formatter));

                PrivateKey key = (PrivateKey) keyStore.getKey(alias, privateKeyPassowrd.toCharArray());
                String pemKey;
                pemKey = "-----BEGIN PRIVATE KEY-----\n";
                pemKey += Base64.encode(key.getEncoded());
                pemKey += "\n-----END PRIVATE KEY-----";
                keyStoreData.setKeyValue(pemKey);
                break;

            }
        }
        return keyStoreData;
    } catch (Exception e) {
        String msg = "Error has encounted while loading the keystore to the given keystore name "
                + keyStoreName;
        log.error(msg, e);
        throw new SecurityConfigException(msg);
    }

}

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 {//  w  w w .j  a va 2 s .  c  o  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);
    }
}