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.tools.ksexplorer.action.ConvertPfx2JksAction.java

public String execute() throws Exception {

    HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
            .get(StrutsStatics.HTTP_REQUEST);
    HttpSession session = request.getSession();

    KeyStore store = null;

    if (KSExplorerConstants.JKS_TO_PFX.equals(conversion)) {
        store = KeyStore.getInstance("jks");
        store.load(new FileInputStream(keyStoreFile), storePasswd.toCharArray());
        session.setAttribute("KeyStore", store);

    } else if (KSExplorerConstants.PFX_TO_JKS.equals(conversion)) {
        store = KeyStore.getInstance("pkcs12");
        store.load(new FileInputStream(keyStoreFile), storePasswd.toCharArray());
        session.setAttribute("KeyStore", store);
        session.setAttribute("StorePass", storePasswd);

    }//  ww w  .j  a  v  a  2  s  .co  m

    Enumeration aliases = store.aliases();

    while (aliases.hasMoreElements()) {
        String alias = (String) aliases.nextElement();

        KeyInfo keyInfo = new KeyInfo();
        keyInfo.setAlias(alias);

        if (store.isKeyEntry(alias)) {
            keyInfo.setPrivateKey(true);
        }

        keyInfoList.add(keyInfo);
    }

    return SUCCESS;
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private List<Map<String, Object>> getKeyStoreInfo(KeyStore store) {
    List<Map<String, Object>> storeEntries = new ArrayList<>();
    try {//from  www.  ja v a 2  s . com
        Enumeration<String> aliases = store.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            Map<String, Object> aliasMap = new HashMap<>();
            Certificate certificate = store.getCertificate(alias);
            boolean isKey = store.isKeyEntry(alias);
            aliasMap.put("alias", alias);
            aliasMap.put("isKey", isKey);
            aliasMap.put("type", certificate.getType());
            aliasMap.put("format", certificate.getPublicKey().getFormat());
            aliasMap.put("algorithm", certificate.getPublicKey().getAlgorithm());
            storeEntries.add(aliasMap);
        }
    } catch (KeyStoreException e) {
        LOGGER.error("Unable to read entries from keystore.", e);
    }
    return storeEntries;
}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSignerTest.java

private String getAlias(KeyStore ks) {
    Certificate[] certificates = null;
    String alias = "";
    Enumeration<String> e;
    try {//  w  ww  .  ja v  a 2 s  .  c o m
        e = ks.aliases();
        while (e.hasMoreElements()) {
            alias = e.nextElement();
            System.out.println("alias..............: " + alias);
            System.out.println("iskeyEntry" + ks.isKeyEntry(alias));
            System.out.println("containsAlias" + ks.containsAlias(alias));
            certificates = ks.getCertificateChain(alias);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return alias;
}

From source file:org.yawlfoundation.yawl.digitalSignature.DigitalSignature.java

private PrivateKey getPrivateKey() {
    KeyStore keystore = null;

    try {//from   ww w. jav a  2 s  . c  o m
        char[] password = _Password.toCharArray();
        String _alias = "";
        _Password = null;
        keystore = KeyStore.getInstance("PKCS12");

        keystore.load(new FileInputStream(_Pathway + _P12), password);

        Enumeration enumeration = keystore.aliases();
        Vector vectaliases = new Vector();
        while (enumeration.hasMoreElements())
            vectaliases.add(enumeration.nextElement());

        String[] aliases = (String[]) (vectaliases.toArray(new String[0]));
        for (int i = 0; i < aliases.length; i++)
            if (keystore.isKeyEntry(aliases[i])) {
                _alias = aliases[i];
                break;
            }
        PrivateKey pk = (PrivateKey) keystore.getKey(_alias, password);
        password = null;
        return pk;

    } catch (Exception e) {
        System.out.println("Error: " + "Invalid pkcs#12 Certificate");
        return null;
    }

}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data,
        String type, String fileName, String path, String storepass, KeyStore store)
        throws KeystoreEditorException {
    OutputStream fos = null;/* w w w  .  j  av  a2  s.  co  m*/
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }
        Path storeFile = Paths.get(path);
        //check the two most common key/cert stores first (pkcs12 and jks)
        if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
            //priv key + cert chain
            KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
            pkcs12Store.load(inputStream, storePassword.toCharArray());
            Certificate[] chain = pkcs12Store.getCertificateChain(alias);
            Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
            if (key != null) {
                store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
            //java keystore file
            KeyStore jks = KeyStore.getInstance("jks");
            jks.load(inputStream, storePassword.toCharArray());
            Enumeration<String> aliases = jks.aliases();

            //we are going to store all entries from the jks regardless of the passed in alias
            while (aliases.hasMoreElements()) {
                String jksAlias = aliases.nextElement();

                if (jks.isKeyEntry(jksAlias)) {
                    Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
                    Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
                    store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
                } else {
                    Certificate certificate = jks.getCertificate(jksAlias);
                    store.setCertificateEntry(jksAlias, certificate);
                }
            }

            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //need to parse der separately from pem, der has the same mime type but is binary hence checking both
        } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
            ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
            ASN1Primitive asn1Primitive = asn1InputStream.readObject();
            X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory
                    .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
            if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                store.setCertificateEntry(cnStr, certificate);
            }
            store.setCertificateEntry(alias, certificate);
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //if it isn't one of the stores we support, it might be a key or cert by itself
        } else if (isPemParsable(type, fileName)) {
            //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            PEMParser pemParser = new PEMParser(reader);
            Object object;
            boolean setEntry = false;
            while ((object = pemParser.readObject()) != null) {
                if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
                    PEMKeyPair pemKeyPair;
                    if (object instanceof PEMEncryptedKeyPair) {
                        PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
                        JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
                        pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(
                                jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
                    } else {
                        pemKeyPair = (PEMKeyPair) object;
                    }

                    KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
                    PrivateKey privateKey = keyPair.getPrivate();
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
                    setEntry = true;
                } else if (object instanceof X509CertificateHolder) {
                    X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
                    Certificate certificate = certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
                    X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate)
                            .getSubject();
                    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                    String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
                    if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                        store.setCertificateEntry(cnStr, certificate);
                    }
                    store.setCertificateEntry(alias, certificate);
                    setEntry = true;
                } else if (object instanceof ContentInfo) {
                    ContentInfo contentInfo = (ContentInfo) object;
                    if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
                        CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
                        OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
                        ASN1Set certificates = originatorInfo.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
                        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
                        ASN1Set certificates = signedData.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    }
                } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    try {
                        store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
                        setEntry = true;
                    } catch (KeyStoreException keyEx) {
                        try {
                            PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(),
                                    keyPassword.toCharArray());
                            store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(),
                                    chain);
                            setEntry = true;
                        } catch (GeneralSecurityException e) {
                            LOGGER.error(
                                    "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.",
                                    e);
                            throw keyEx;
                        }
                    }
                }
            }
            if (setEntry) {
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Unable to add entry {} to store", alias, e);
        throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }
    init();
}

From source file:com.verisign.epp.codec.launch.EPPLaunchTst.java

/**
 * Loads the private key used to digitally sign from a Java KeyStore with
 * the alias of the <code>PrivateKeyEntry</code> and the password to access
 * the Keystore and the key./*  w  ww .  j  a  v a 2 s.  c om*/
 * 
 * @param aKeyStoreName
 *            Java Keystore to load the key from
 * @param aKeyAliasName
 *            Java Keystore alias of key
 * @param aPassword
 *            Password to access Java Keystore and key
 * 
 * @return Loaded <code>KeyStore.PrivateKeyEntry</code> that can be used to
 *         get the private key and it's associated certificate chain.
 * 
 * @throws Exception
 *             Error loading private key
 */
private static KeyStore.PrivateKeyEntry loadPrivateKeyEntry(String aKeyStoreName, String aKeyAliasName,
        String aPassword) throws Exception {

    // Load KeyStore
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream keyStoreFile = new FileInputStream(aKeyStoreName);
    keyStore.load(keyStoreFile, aPassword.toCharArray());

    // Get Private Key
    assert keyStore.isKeyEntry(aKeyAliasName);
    KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(aKeyAliasName,
            new KeyStore.PasswordProtection(aPassword.toCharArray()));

    return keyEntry;
}

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

public void addKeyStore(byte[] content, String filename, String password, String provider, String type,
        String pvtkeyPass) throws SecurityConfigException {
    if (filename == null) {
        throw new SecurityConfigException("Key Store name can't be null");
    }/*from   w  ww.j a  va 2s . c o m*/
    try {
        if (KeyStoreUtil.isPrimaryStore(filename)) {
            throw new SecurityConfigException("Key store " + filename + " already available");
        }

        String path = SecurityConstants.KEY_STORES + "/" + filename;
        if (registry.resourceExists(path)) {
            throw new SecurityConfigException("Key store " + filename + " already available");
        }

        KeyStore keyStore = KeyStore.getInstance(type);
        keyStore.load(new ByteArrayInputStream(content), password.toCharArray());

        // check for more private keys
        Enumeration enumeration = keyStore.aliases();
        String pvtKeyAlias = null;
        while (enumeration.hasMoreElements()) {
            String alias = (String) enumeration.nextElement();
            if (keyStore.isKeyEntry(alias)) {
                if (pvtKeyAlias == null) {
                    pvtKeyAlias = alias;
                } else {
                    // more than one private key
                    throw new SecurityConfigException("more than one private key");
                }
            }
        }

        // just to test weather pvt key password is correct.
        keyStore.getKey(pvtKeyAlias, pvtkeyPass.toCharArray());

        CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();

        Resource resource = registry.newResource();
        resource.addProperty(SecurityConstants.PROP_PASSWORD,
                cryptoUtil.encryptAndBase64Encode(password.getBytes()));
        resource.addProperty(SecurityConstants.PROP_PROVIDER, provider);
        resource.addProperty(SecurityConstants.PROP_TYPE, type);

        if (pvtKeyAlias != null) {
            resource.addProperty(SecurityConstants.PROP_PRIVATE_KEY_ALIAS, pvtKeyAlias);
            resource.addProperty(SecurityConstants.PROP_PRIVATE_KEY_PASS,
                    cryptoUtil.encryptAndBase64Encode(pvtkeyPass.getBytes()));
        }

        resource.setContent(content);
        registry.put(path, resource);
    } catch (SecurityConfigException e) {
        throw e;
    } catch (Exception e) {
        String msg = "Error when adding a keyStore";
        log.error(msg, e);
        throw new SecurityConfigException(msg, e);
    }
}

From source file:mitm.djigzo.web.pages.certificate.CertificateImportKey.java

private void importPfx() throws KeyStoreException, NoSuchProviderException, SecurityFactoryFactoryException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableEntryException,
        WebServiceCheckedException {//from  ww w .j a va2  s.  c  om
    /*
     * To prevent timeouts on the SOAP connection we should upload the PFX file in batches if the PFX file
     * contains a large number of entries. The PFX file should therefore be opened. 
     */
    KeyStore allKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    if (password == null) {
        password = "";
    }

    allKeys.load(file.getStream(), password.toCharArray());

    KeyAndCertificateWorkflow.MissingKey missingKey = ignoreMissingKey
            ? KeyAndCertificateWorkflow.MissingKey.SKIP_CERTIFICATE
            : KeyAndCertificateWorkflow.MissingKey.ADD_CERTIFICATE;

    int imported = 0;

    KeyStore batchKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");
    batchKeys.load(null, password.toCharArray());

    Enumeration<String> aliases = allKeys.aliases();

    KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(password.toCharArray());

    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();

        if (allKeys.isKeyEntry(alias)) {
            KeyStore.Entry entry = allKeys.getEntry(alias, passwordProtection);

            batchKeys.setEntry(alias, entry, passwordProtection);
        } else {
            Certificate certificate = allKeys.getCertificate(alias);

            batchKeys.setCertificateEntry(alias, certificate);
        }

        if (batchKeys.size() >= maxBatchSize) {
            imported += uploadKeyStore(batchKeys, missingKey, password);

            batchKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");
            batchKeys.load(null, password.toCharArray());
        }
    }

    /*
     * Check if there are still some entries left to add (happens when the number
     * of entries is not a multiple of maxBatchSize)
     */
    if (batchKeys.size() > 0) {
        imported += uploadKeyStore(batchKeys, missingKey, password);
    }

    this.importCount = imported;
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplTest.java

/**
 * Test method for {@link net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl#exportKeyPair(java.lang.String, java.io.File, java.lang.String)}.
 * @throws CMException /*from  ww  w.j av  a 2s  .  c  o m*/
 * @throws KeyStoreException 
 * @throws NoSuchAlgorithmException 
 * @throws UnrecoverableKeyException 
 */
@Test
public void testExportKeyPair()
        throws CMException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
    String alias = credentialManager.addKeyPair(privateKey, privateKeyCertChain);
    File fileToExportTo = new File(credentialManagerDirectory, "test-export-key.p12");
    credentialManager.exportKeyPair(alias, fileToExportTo, privateKeyAndPKCS12KeystorePassword);
    assertTrue(fileToExportTo.exists());
    // Load it back from the file we just saved
    KeyStore ks = credentialManager.loadPKCS12Keystore(fileToExportTo, privateKeyAndPKCS12KeystorePassword);
    Enumeration<String> aliases = ks.aliases();
    Key newPrivateKey = null;
    Certificate[] newPrivateKeyCerts = null;
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        alias = aliases.nextElement();
        if (ks.isKeyEntry(alias)) { // is it a (private) key entry?
            newPrivateKey = ks.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            newPrivateKeyCerts = ks.getCertificateChain(alias);
            break;
        }
    }
    assertNotNull(newPrivateKey);
    assertNotNull(newPrivateKeyCerts);
    //assertTrue(Arrays.equals(newPrivateKey.getEncoded(), privateKey.getEncoded()));
    assertTrue(newPrivateKey.equals(privateKey));
    assertTrue(Arrays.equals(newPrivateKeyCerts, privateKeyCertChain));
}

From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImplTest.java

/**
 * Test method for {@link org.apache.taverna.security.credentialmanager.impl.CredentialManagerImpl#exportKeyPair(java.lang.String, java.io.File, java.lang.String)}.
 * @throws CMException //ww  w.ja v  a 2s.  c o  m
 * @throws KeyStoreException 
 * @throws NoSuchAlgorithmException 
 * @throws UnrecoverableKeyException 
 */
@Test
public void testExportKeyPair()
        throws CMException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
    String alias = credentialManager.addKeyPair(privateKey, privateKeyCertChain);
    File fileToExportTo = new File(credentialManagerDirectory, "test-export-key.p12");
    credentialManager.exportKeyPair(alias, fileToExportTo.toPath(), privateKeyAndPKCS12KeystorePassword);
    assertTrue(fileToExportTo.exists());
    // Load it back from the file we just saved
    KeyStore ks = credentialManager.loadPKCS12Keystore(fileToExportTo.toPath(),
            privateKeyAndPKCS12KeystorePassword);
    Enumeration<String> aliases = ks.aliases();
    Key newPrivateKey = null;
    Certificate[] newPrivateKeyCerts = null;
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        alias = aliases.nextElement();
        if (ks.isKeyEntry(alias)) { // is it a (private) key entry?
            newPrivateKey = ks.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            newPrivateKeyCerts = ks.getCertificateChain(alias);
            break;
        }
    }
    assertNotNull(newPrivateKey);
    assertNotNull(newPrivateKeyCerts);
    //assertTrue(Arrays.equals(newPrivateKey.getEncoded(), privateKey.getEncoded()));
    assertTrue(newPrivateKey.equals(privateKey));
    assertTrue(Arrays.equals(newPrivateKeyCerts, privateKeyCertChain));
}