Example usage for java.security KeyStore containsAlias

List of usage examples for java.security KeyStore containsAlias

Introduction

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

Prototype

public final boolean containsAlias(String alias) throws KeyStoreException 

Source Link

Document

Checks if the given alias exists in this keystore.

Usage

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static void add(File keystore, KeyPair pair, String domain) {
    if (keystore == null) {
        throw new IllegalArgumentException("Key Store file should not be null.");
    }//from www.  j  a  v  a  2s. c  o  m

    try {
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        if (keystore.exists()) {
            FileInputStream stream = new FileInputStream(keystore);
            ks.load(stream, SECRET);
            IOUtils.closeQuietly(stream);
        } else {
            ks.load(null, SECRET);
        }

        if (!ks.containsAlias(ALIAS)) {
            X509Certificate certificate = generateCertificate(domain, 1, pair);

            ks.setKeyEntry(ALIAS, pair.getPrivate(), SECRET, new Certificate[] { certificate });

            FileOutputStream stream = new FileOutputStream(keystore);
            ks.store(stream, SECRET);
            IOUtils.closeQuietly(stream);
        }
    } catch (Throwable th) {
        logger.error("Failed to initialize key store");
        throw new OpenFlameRuntimeException(th.getMessage(), th);
    }
}

From source file:org.paxml.util.CryptoUtils.java

private static String getKey(KeyStore keyStore, String keyName, String keyPassword) {
    if (StringUtils.isBlank(keyName)) {
        keyName = DEFAULT_KEY_NAME;//  w  w w  .  ja v a 2s  .com
    }
    if (keyPassword == null) {
        keyPassword = DEFAULT_KEY_PASSWORD;
    }
    PasswordProtection _keyPassword = new PasswordProtection(keyPassword.toCharArray());
    KeyStore.Entry entry;
    try {
        if (!keyStore.containsAlias(keyName)) {
            return null;
        }
        entry = keyStore.getEntry(keyName, _keyPassword);
    } catch (Exception e) {
        throw new PaxmlRuntimeException(e);
    }
    SecretKey key = ((KeyStore.SecretKeyEntry) entry).getSecretKey();
    try {
        return new String(key.getEncoded(), KEY_VALUE_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw new PaxmlRuntimeException(e);
    }

}

From source file:org.nuxeo.common.codec.Crypto.java

/**
 * Extract secret keys from a keystore looking for {@code keyAlias + algorithm}
 *
 * @param keystorePath Path to the keystore
 * @param keystorePass Keystore password
 * @param keyAlias Key alias prefix. It is suffixed with the algorithm.
 * @param keyPass Key password/*from ww w  . j  a v  a 2 s.co  m*/
 * @throws GeneralSecurityException
 * @throws IOException
 * @see #IMPLEMENTED_ALGOS
 */
public static Map<String, SecretKey> getKeysFromKeyStore(String keystorePath, char[] keystorePass,
        String keyAlias, char[] keyPass) throws GeneralSecurityException, IOException {
    KeyStore keystore = KeyStore.getInstance("JCEKS");
    try (InputStream keystoreStream = new FileInputStream(keystorePath)) {
        keystore.load(keystoreStream, keystorePass);
    }
    Map<String, SecretKey> secretKeys = new HashMap<>();
    for (String algo : IMPLEMENTED_ALGOS) {
        if (keystore.containsAlias(keyAlias + algo)) {
            SecretKey key = (SecretKey) keystore.getKey(keyAlias + algo, keyPass);
            secretKeys.put(algo, key);
        }
    }
    if (secretKeys.isEmpty()) {
        throw new KeyStoreException(String.format("No alias \"%s<algo>\" found in %s", keyAlias, keystorePath));
    }
    return secretKeys;
}

From source file:org.adempierelbr.model.MLBRDigitalCertificate.java

/**
 * setCertificate/*from  w ww .  j  a  v  a2 s  .c  o  m*/
 * Set all System.property for webservice connection
 */
public static void setCertificate(Properties ctx, MOrgInfo oi) throws Exception {

    Integer certOrg = (Integer) oi.get_Value("LBR_DC_Org_ID");
    Integer certWS = (Integer) oi.get_Value("LBR_DC_WS_ID");
    MLBRDigitalCertificate dcOrg = new MLBRDigitalCertificate(Env.getCtx(), certOrg, null);
    MLBRDigitalCertificate dcWS = new MLBRDigitalCertificate(Env.getCtx(), certWS, null);

    String orgPassword = dcOrg.getPassword();
    String certType = null;
    InputStream certFileOrg = null;

    if (MLBRDigitalCertificate.LBR_CERTTYPE_PKCS12.equals(dcOrg.getlbr_CertType())) {
        certType = "PKCS12";
        certFileOrg = dcOrg.getAttachment(true).getEntry(0).getInputStream();
        if (certFileOrg == null)
            throw new Exception("Unable to find private key attachment");
    } else if (MLBRDigitalCertificate.LBR_CERTTYPE_PKCS11.equals(dcOrg.getlbr_CertType())) {
        certType = "PKCS11";
        Provider p = new sun.security.pkcs11.SunPKCS11(dcOrg.getConfigurationFile());
        Security.addProvider(p);
    } else
        return; //   Unknown Certificate

    KeyStore ks = KeyStore.getInstance(certType);
    try {
        ks.load(certFileOrg, orgPassword.toCharArray());
    } catch (IOException e) {
        throw new Exception("Incorrect Certificate Password");
    }

    InputStream certFileWS = dcWS.getAttachment(true).getEntry(0).getInputStream();
    if (certFileWS == null) {
        throw new Exception("Unable to find webservices keystore attachment");
    }

    String alias = dcOrg.getAlias();
    if (alias != null && ks.containsAlias(alias) && ks.isKeyEntry(alias))
        ;//   Do Nothing
    else {
        Enumeration<String> aliasesEnum = ks.aliases();
        while (aliasesEnum.hasMoreElements()) {
            alias = (String) aliasesEnum.nextElement();
            if (ks.isKeyEntry(alias))
                break;
        }
    }

    //Erro NFe 3.10
    System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");

    X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
    PrivateKey privateKey = (PrivateKey) ks.getKey(alias, orgPassword.toCharArray());
    SocketFactoryDinamico socketFactoryDinamico = new SocketFactoryDinamico(certificate, privateKey);
    socketFactoryDinamico.setFileCacerts(certFileWS, dcWS.getPassword());

    Protocol protocol = new Protocol("https", socketFactoryDinamico, 443);
    Protocol.registerProtocol("https", protocol);
}

From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java

/**
 * Remove a key with the specified alias from the keystore.
 * @param keyStore to remove from//from w w w.ja  v  a  2  s .  c o m
 * @param alias of key to remove
 * @return true if the key alias was removed
 * @throws CryptoTokenOfflineException if the keystore was null
 * @throws KeyStoreException for keystore related errors
 * @throws SignServerException if the keystore did not contain a key with the specified alias
 */
public static boolean removeKey(final KeyStore keyStore, final String alias)
        throws CryptoTokenOfflineException, KeyStoreException, SignServerException {
    if (keyStore == null) {
        throw new CryptoTokenOfflineException("Token offline");
    }
    if (!keyStore.containsAlias(alias)) {
        throw new SignServerException("No such alias in token: " + alias);
    }
    keyStore.deleteEntry(alias);
    return !keyStore.containsAlias(alias);
}

From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java

private static SSLContext sslContext() {
    final String property = SettingsManager.settings().ssl();
    if (property != null && !property.isEmpty() && !"null".equals(property)) {
        if ("trustanything".equals(property)) {
            try {
                return SSLContexts.custom().loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()),
                        new TrustStrategy() {
                            public boolean isTrusted(X509Certificate[] chain, String authType)
                                    throws CertificateException {
                                return true;
                            }/*from   w  w  w. j ava 2 s  .c o  m*/
                        }).build();
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        } else {
            try {
                String location = property;
                location = location.equals("compatible")
                        ? "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt"
                        : location;
                File cachedPemFile = new File("./pemfile_cached");
                boolean remote = location.startsWith("https://") || location.startsWith("http://");
                if (remote && cachedPemFile.exists()
                        && (System.currentTimeMillis() - cachedPemFile.lastModified() < 48 * 60 * 60 * 1000)) {
                    location = cachedPemFile.getAbsolutePath();
                    remote = false;
                }
                String pemBlocks = null;
                if (remote) {
                    HttpURLConnection remotePemFile = (HttpURLConnection) StreamHandler
                            .defaultConnection(new URL(location));
                    remotePemFile.setRequestMethod("GET");
                    remotePemFile.connect();
                    pemBlocks = Util.toString(remotePemFile.getInputStream(), Util.charset(remotePemFile));
                    cachedPemFile.delete();
                    Files.write(Paths.get(cachedPemFile.getAbsolutePath()), pemBlocks.getBytes("utf-8"));
                } else {
                    pemBlocks = new String(Files.readAllBytes(Paths.get(new File(location).getAbsolutePath())),
                            "utf-8");
                }
                KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                keyStore.load(null);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                Matcher matcher = pemBlock.matcher(pemBlocks);
                boolean found = false;
                while (matcher.find()) {
                    String pemBlock = matcher.group(1).replaceAll("[\\n\\r]+", "");
                    ByteArrayInputStream byteStream = new ByteArrayInputStream(
                            Base64.getDecoder().decode(pemBlock));
                    java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) cf
                            .generateCertificate(byteStream);
                    String alias = cert.getSubjectX500Principal().getName("RFC2253");
                    if (alias != null && !keyStore.containsAlias(alias)) {
                        found = true;
                        keyStore.setCertificateEntry(alias, cert);
                    }
                }
                if (found) {
                    KeyManagerFactory keyManager = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    keyManager.init(keyStore, null);
                    TrustManagerFactory trustManager = TrustManagerFactory
                            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    trustManager.init(keyStore);
                    SSLContext context = SSLContext.getInstance("TLS");
                    context.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
                    return context;
                }
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        }
    }
    return SSLContexts.createSystemDefault();
}

From source file:eu.europa.esig.dss.x509.KeyStoreCertificateSource.java

public void deleteCertificateFromKeyStore(String dssId) {
    KeyStore keyStore = getKeyStore();
    try {// ww w.j  a  v  a  2s. c o  m
        if (keyStore.containsAlias(dssId)) {
            keyStore.deleteEntry(dssId);
            persistKeyStore(keyStore);
            logger.info("Certificate with ID " + dssId + " successfuly removed from the keystore");
        } else {
            logger.warn("Certificate " + dssId + " not found in the keystore");
        }
    } catch (Exception e) {
        logger.error("Unable to delete certificate from the keystore : " + e.getMessage(), e);
    }
}

From source file:org.metaeffekt.dcc.commons.ant.CreateKeystoreTaskTest.java

private void assertValidKeystore(String keystoreFile, String keystoreType, String alias, String password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        FileNotFoundException {/*  ww w.  j av a2  s .c om*/
    KeyStore store = KeyStore.getInstance(keystoreType);
    FileInputStream keystore = new FileInputStream(keystoreFile);
    try {
        store.load(keystore, password.toCharArray());
        assertTrue(store.containsAlias(alias));
    } finally {
        IOUtils.closeQuietly(keystore);
    }
}

From source file:org.apache.hadoop.gateway.services.security.impl.BaseKeystoreService.java

public void removeCredential(String alias, KeyStore ks) {
    if (ks != null) {
        try {// w  ww .j  a va2 s.  c  o m
            if (ks.containsAlias(alias)) {
                ks.deleteEntry(alias);
            }
        } catch (KeyStoreException e) {
            LOG.failedToAddCredential(e);
        }
    }
}

From source file:gov.nih.nci.cacisweb.action.SecureFTPAddAction.java

@Override
public String execute() throws Exception {
    log.debug("execute() - START");
    String secureFTPPropertyFileLocation = CaCISUtil
            .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_PROPERTIES_FILE_LOCATION);
    String secureFTPKeystoreLocation = CaCISUtil.getPropertyFromPropertiesFile(secureFTPPropertyFileLocation,
            CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_TRUSTSTORE_LOCATION_PROP_NAME));
    String secureFTPKeystorePassword = CaCISUtil.getPropertyFromPropertiesFile(secureFTPPropertyFileLocation,
            CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_TRUSTSTORE_PASSWORD_PROP_NAME));
    try {/* w  w w .  j a v  a  2 s  . co m*/
        CaCISUtil caCISUtil = new CaCISUtil();
        KeyStore keystore = caCISUtil.getKeystore(secureFTPKeystoreLocation,
                CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, secureFTPKeystorePassword);

        if (keystore.containsAlias(secureFTPBean.getCertificateAlias())) {
            log.error(getText("secureFTPBean.duplicateKey"));
            addFieldError("secureFTPBean.certificateAlias", getText("secureFTPBean.duplicateKey"));
        }

        if (StringUtils.contains(secureFTPBean.getCertificateAlias(), "ftps")) {
            if (StringUtils.isBlank(secureFTPBean.getCertificateFileName())) {
                log.error(getText("secureFTPBean.certificateRequired"));
                addFieldError("secureFTPBean.certificateFileName",
                        getText("secureFTPBean.certificateRequired"));
                caCISUtil.releaseKeystore();
                return INPUT;
            } else {
                caCISUtil.releaseKeystore();
                FileInputStream certificateStream = new FileInputStream(secureFTPBean.getCertificate());

                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                java.security.cert.Certificate cert = cf.generateCertificate(certificateStream);
                // Add the certificate
                keystore.setCertificateEntry(secureFTPBean.getCertificateAlias(), cert);

                // Save the new keystore contents
                FileOutputStream out = new FileOutputStream(new File(secureFTPKeystoreLocation));
                keystore.store(out, secureFTPKeystorePassword.toCharArray());
                out.close();
            }
        }

        // add the new entry to FTP configuration properties file
        PropertiesConfiguration config = new PropertiesConfiguration(
                CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_CONFIG_FILE_LOCATION));
        config.setProperty(secureFTPBean.getCertificateAlias(), "");
        config.save();
    } catch (KeystoreInstantiationException kie) {
        log.error(kie.getMessage());
        addActionError(getText("exception.keystoreInstantiation"));
        return ERROR;
    } catch (CertificateException ce) {
        log.error(CaCISUtil.getStackTrace(ce));
        addActionError(getText("exception.certification"));
        return INPUT;
    }
    addActionMessage(getText("secureFTPBean.addCertificateSuccessful"));
    log.debug("execute() - END");
    return SUCCESS;
}