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:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java

private static final void importCertificate(final String url, final KeyStore trustStore) throws Exception {
    final URL url2 = new URL(url);
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    final X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
    final SavingTrustManager trustManager = new SavingTrustManager(defaultTrustManager);
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(url2.getHost(),
            url2.getPort() > 0 ? url2.getPort() : 443);
    socket.setSoTimeout(10000);//from   ww w  .ja  v  a 2 s.c  om
    try {
        socket.startHandshake();
        socket.close();
    } catch (SSLException e) {
    }

    final X509Certificate[] chain = trustManager.chain;
    if (chain == null) {
        LOGGER.error("Could not obtain server certificate chain from: " + url);
        return;
    }

    final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    final MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        final X509Certificate cert = chain[i];
        final String alias = url2.getHost() + "-" + (i + 1);
        if (!trustStore.containsAlias(alias)) {
            sha1.update(cert.getEncoded());
            md5.update(cert.getEncoded());
            LOGGER.trace("Importing certificate to trusted keystore >> " + "Subject: " + cert.getSubjectDN()
                    + ", Issuer: " + cert.getIssuerDN() + ", SHA1: " + printHexBinary(sha1.digest()) + ", MD5: "
                    + printHexBinary(md5.digest()) + ", Alias: " + alias);
            trustStore.setCertificateEntry(alias, cert);
        }
    }
}

From source file:org.ejbca.ui.web.pub.CertRequestHttpTest.java

/**
 * Tests request for a pkcs12/*from  www  .  j av a 2  s . c  om*/
 * 
 * @throws Exception error
 */
@Test
public void test01RequestPKCS12() throws Exception {
    log.trace(">test01RequestPKCS12()");

    // find a CA (TestCA?) create a user
    // Send certificate request for a server generated PKCS12
    setupUser(SecConst.TOKEN_SOFT_P12);
    setupUserStatus(EndEntityConstants.STATUS_NEW);

    // POST the OCSP request
    URL url = new URL(httpReqPath + '/' + resourceReq);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    // we are going to do a POST
    con.setDoOutput(true);
    con.setRequestMethod("POST");

    // POST it
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    OutputStream os = con.getOutputStream();
    os.write(("user=" + TEST_USERNAME + "&password=foo123&keylength=2048").getBytes("UTF-8"));
    os.close();
    assertEquals("Response code", 200, con.getResponseCode());
    // Some appserver (Weblogic) responds with
    // "application/x-pkcs12; charset=UTF-8"
    String contentType = con.getContentType();
    boolean contentTypeIsPkcs12 = contentType.startsWith("application/x-pkcs12");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // This works for small requests, and PKCS12 requests are small
    InputStream in = con.getInputStream();
    int b = in.read();
    while (b != -1) {
        baos.write(b);
        b = in.read();
    }
    baos.flush();
    in.close();
    byte[] respBytes = baos.toByteArray();
    assertTrue(respBytes.length > 0);
    if (!contentTypeIsPkcs12 && log.isDebugEnabled()) {
        // If the content-type isn't application/x-pkcs12 we like to know what we got back..
        log.debug(new String(respBytes));
    }
    assertTrue("contentType was " + contentType, contentTypeIsPkcs12);

    KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    ByteArrayInputStream is = new ByteArrayInputStream(respBytes);
    store.load(is, "foo123".toCharArray());
    assertTrue(store.containsAlias("ReqTest"));
    X509Certificate cert = (X509Certificate) store.getCertificate("ReqTest");
    PublicKey pk = cert.getPublicKey();
    if (pk instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pk;
        assertEquals(rsapk.getAlgorithm(), "RSA");
        assertEquals(2048, rsapk.getModulus().bitLength());
    } else {
        assertTrue("Public key is not RSA", false);
    }

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

From source file:it.cnr.icar.eric.common.security.KeystoreMover.java

public void move(String sourceKeystoreType, String sourceKeystorePath, String sourceKeystorePassword,
        String sourceAlias, String sourceKeyPassword, String destinationKeystoreType,
        String destinationKeystorePath, String destinationKeystorePassword, String destinationAlias,
        String destinationKeyPassword) throws Exception {

    char[] sourceKeystorePasswordArr = null;
    if (sourceKeystorePassword != null) {
        sourceKeystorePasswordArr = sourceKeystorePassword.toCharArray();
    }//from   ww w . j a v  a  2  s  . c om

    char[] sourceKeyPasswordArr = sourceKeystorePasswordArr;
    if (sourceKeyPassword != null) {
        sourceKeyPasswordArr = sourceKeyPassword.toCharArray();
    }

    char[] destinationKeystorePasswordArr = null;
    if (destinationKeystorePassword != null) {
        destinationKeystorePasswordArr = destinationKeystorePassword.toCharArray();
    }

    char[] destinationKeyPasswordArr = destinationKeystorePasswordArr;
    if (destinationKeyPassword != null) {
        destinationKeyPasswordArr = destinationKeyPassword.toCharArray();
    }

    FileInputStream in;

    // --------  Load source keystore to memory ---------
    in = new FileInputStream(sourceKeystorePath);
    KeyStore ksin = KeyStore.getInstance(sourceKeystoreType);

    ksin.load(in, sourceKeystorePasswordArr);
    in.close();

    // --------  Load destination keystore initial contents to memory ---------
    KeyStore ksout = KeyStore.getInstance(destinationKeystoreType);

    try {
        in = new FileInputStream(destinationKeystorePath);
        ksout.load(in, destinationKeystorePasswordArr);
    } catch (java.io.FileNotFoundException e) {
        ksout.load(null, destinationKeystorePasswordArr);
    } finally {
        in.close();
    }

    Enumeration<String> en = ksin.aliases();
    while (en.hasMoreElements()) {
        String alias = en.nextElement();

        if ((sourceAlias == null) || (sourceAlias.equalsIgnoreCase(alias))) {

            if (ksout.containsAlias(alias)) {
                log.info(CommonResourceBundle.getInstance().getString(
                        "message.destinationKeystorePathAlreadyContains",
                        new Object[] { destinationKeystorePath, alias }));
                continue;
            }

            //Use existing alias if no destinationAlias specified
            if (destinationAlias == null) {
                destinationAlias = alias;
            }

            if (ksin.isCertificateEntry(alias)) {
                log.debug(CommonResourceBundle.getInstance().getString("message.importingCertificate",
                        new Object[] { alias }));
                ksout.setCertificateEntry(destinationAlias, ksin.getCertificate(alias));
            }

            if (ksin.isKeyEntry(alias)) {
                log.debug(CommonResourceBundle.getInstance().getString("message.importingKey",
                        new Object[] { alias }));
                Certificate[] certChain = ksin.getCertificateChain(alias);
                ksout.setKeyEntry(destinationAlias, ksin.getKey(alias, sourceKeyPasswordArr),
                        destinationKeyPasswordArr, certChain);
            }
        }

    }

    //---------  Overwrite the destination keystore with new keys/certs which is a merge of source and original destination keystores--------------
    FileOutputStream out = new FileOutputStream(destinationKeystorePath);
    ksout.store(out, destinationKeystorePasswordArr);
    out.close();
    log.debug(CommonResourceBundle.getInstance().getString("message.keystoreCopySuccessful"));
}

From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * This method generates a certificate from a base64 encoded certificate string and add to the configured trust
 * store./*  ww w  .  j  av a2  s. com*/
 *
 * @param base64Cert : The base 64 encoded string of the server certificate.
 * @param alias      : The alias for the certificate.
 * @return : ResponseCode which matches the execution result.
 *
 * Response Codes.
 * SUCCESS : If certificate added successfully.
 * INTERNAL_SERVER_ERROR : If any internal error occurred
 * ALIAS_EXISTS_IN_TRUST_STORE : If the alias exists in trust store.
 * CERTIFICATE_EXPIRED : If the given certificate is expired.
 */
public ResponseCode addCertificateToTrustStore(String base64Cert, String alias) {

    boolean isCertExists = false;
    boolean expired = false;
    InputStream serverCert = null;
    try {
        //Decode base64 encoded certificate.
        byte[] cert = (Base64.decodeBase64(base64Cert.getBytes(CHARSET_UTF_8)));
        serverCert = new ByteArrayInputStream(cert);
        if (serverCert.available() == 0) {
            log.error("Certificate is empty for the provided alias " + alias);
            return ResponseCode.INTERNAL_SERVER_ERROR;
        }

        //Read the client-truststore.jks into a KeyStore.
        File trustStoreFile = new File(TRUST_STORE);
        localTrustStoreStream = new FileInputStream(trustStoreFile);
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD);

        CertificateFactory cf = CertificateFactory.getInstance(CERTIFICATE_TYPE);
        while (serverCert.available() > 0) {
            Certificate certificate = cf.generateCertificate(serverCert);
            //Check whether the Alias exists in the trust store.
            if (trustStore.containsAlias(alias)) {
                isCertExists = true;
            } else {
                /*
                * If alias is not exists, check whether the certificate is expired or not. If expired set the
                * expired flag.
                * */
                X509Certificate x509Certificate = (X509Certificate) certificate;
                if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) {
                    expired = true;
                    if (log.isDebugEnabled()) {
                        log.debug("Provided certificate is expired.");
                    }
                } else {
                    //If not expired add the certificate to trust store.
                    trustStore.setCertificateEntry(alias, certificate);
                }
            }
        }
        fileOutputStream = new FileOutputStream(trustStoreFile);
        trustStore.store(fileOutputStream, TRUST_STORE_PASSWORD);
        responseCode = expired ? ResponseCode.CERTIFICATE_EXPIRED
                : isCertExists ? ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE : ResponseCode.SUCCESS;
    } catch (CertificateException e) {
        log.error("Error loading certificate.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (FileNotFoundException e) {
        log.error("Error reading/ writing to the certificate file.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (NoSuchAlgorithmException e) {
        log.error("Could not find the algorithm to load the certificate.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (UnsupportedEncodingException e) {
        log.error("Error retrieving certificate from String", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (KeyStoreException e) {
        log.error("Error reading certificate contents.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (IOException e) {
        log.error("Error in loading the certificate.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } finally {
        closeStreams(localTrustStoreStream, fileOutputStream, serverCert);
    }
    return responseCode;
}

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

private boolean validKeystoreAlias(String alias, String keystorePassword, String keystoreData,
        String keystoreFileName) throws KeystoreEditorException {
    boolean valid = false;
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(keystoreData))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }//  w  ww  .  j  av  a 2  s  . c om
        KeyStore ks = null;
        if (StringUtils.endsWithIgnoreCase(keystoreFileName, ".p12")) {
            ks = KeyStore.getInstance("PKCS12");
        } else if (StringUtils.endsWithIgnoreCase(keystoreFileName, ".jks")) {
            ks = KeyStore.getInstance("jks");
        }

        if (ks != null) {
            ks.load(inputStream, keystorePassword.toCharArray());
            valid = ks.containsAlias(alias);
        }
    } catch (Exception e) {
        LOGGER.error("Unable read keystore data.", e);
        throw new KeystoreEditorException("Unable read keystore data.", e);
    }
    return valid;
}

From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java

@Test
public void testGetCertificateAuthnCertCredential() throws Exception {
    LOG.debug("sign");
    // operate// www .ja va 2  s. com
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    Security.addProvider(new HSMProxyProvider());
    KeyStore hsmProxyKeyStore = KeyStore.getInstance("HSMProxy");

    HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter(authnPrivateKey, authnCert,
            // "https://www.e-contract.be/hsm-proxy-ws/dss",
            "http://localhost/hsm-proxy-ws/dss", new MyHSMProxyAudit());
    hsmProxyKeyStore.load(keyStoreParameter);

    Enumeration<String> aliasesEnum = hsmProxyKeyStore.aliases();
    assertNotNull(aliasesEnum);
    while (aliasesEnum.hasMoreElements()) {
        String alias = aliasesEnum.nextElement();
        LOG.debug("alias: " + alias);
        X509Certificate certificate = (X509Certificate) hsmProxyKeyStore.getCertificate(alias);
        assertNotNull(certificate);
        LOG.debug("certificate: " + certificate);
        assertTrue(hsmProxyKeyStore.containsAlias(alias));
        Certificate[] certificateChain = hsmProxyKeyStore.getCertificateChain(alias);
        assertNotNull(certificateChain);
        PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) hsmProxyKeyStore.getEntry(alias, null);
        assertNotNull(privateKeyEntry);
    }
}

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  . jav a2  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:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testBeIDSignature() throws Exception {
    Security.addProvider(new BeIDProvider());

    final KeyStore keyStore = KeyStore.getInstance("BeID");
    final BeIDKeyStoreParameter keyStoreParameter = new BeIDKeyStoreParameter();
    final BeIDCard beIDCard = getBeIDCard();
    keyStoreParameter.setBeIDCard(beIDCard);
    keyStoreParameter.setLogoff(true);//from  w w  w  .j av a2s  .c o  m
    keyStore.load(keyStoreParameter);

    final Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        final String alias = aliases.nextElement();
        LOG.debug("alias: " + alias);
    }

    assertEquals(2, keyStore.size());

    assertTrue(keyStore.containsAlias("Signature"));
    assertTrue(keyStore.containsAlias("Authentication"));
    assertNotNull(keyStore.getCreationDate("Signature"));
    assertNotNull(keyStore.getCreationDate("Authentication"));

    assertTrue(keyStore.isKeyEntry("Signature"));
    final X509Certificate signCertificate = (X509Certificate) keyStore.getCertificate("Signature");
    assertNotNull(signCertificate);

    assertTrue(keyStore.isKeyEntry("Authentication"));
    final X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    assertNotNull(authnCertificate);

    assertNotNull(keyStore.getCertificateChain("Signature"));
    assertNotNull(keyStore.getCertificateChain("Authentication"));

    assertTrue(keyStore.isKeyEntry("Authentication"));
    final PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    assertNotNull(authnPrivateKey);

    assertTrue(keyStore.isKeyEntry("Signature"));
    final PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null);
    assertNotNull(signPrivateKey);

    verifySignatureAlgorithm("SHA1withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA256withRSA", signPrivateKey, signCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA384withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA512withRSA", authnPrivateKey, authnCertificate.getPublicKey());

    Security.addProvider(new BouncyCastleProvider());

    verifySignatureAlgorithm("SHA1withRSAandMGF1", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA256withRSAandMGF1", authnPrivateKey, authnCertificate.getPublicKey());
}

From source file:gov.nih.nci.cacisweb.util.CaCISUtil.java

/**
 * //from  www  .j  a  va 2 s.  c o m
 * @param propertyFileLocation
 * @param keyStoreLocation
 * @param keyStoreType
 * @param keyStorePassword
 * @return
 * @throws PropFileAndKeystoreOutOfSyncException
 */
public boolean isPropertyFileAndKeystoreInSync(String propertyFileLocation, String keyStoreLocation,
        String keyStoreType, String keyStorePassword) throws PropFileAndKeystoreOutOfSyncException {
    boolean isInSync = false;
    try {
        Properties configFile = new Properties();
        InputStream is = new FileInputStream(propertyFileLocation);
        configFile.load(is);
        is.close();
        KeyStore keystore = getKeystore(keyStoreLocation, keyStoreType, keyStorePassword);
        // Enumeration<String> keystoreEnumeration = keystore.aliases();
        // while (keystoreEnumeration.hasMoreElements()) {
        // String alias = (String) keystoreEnumeration.nextElement();
        // if (!configFile.containsKey(alias)) {
        // isInSync = false;
        // throw new PropFileAndKeystoreOutOfSyncException(String.format(
        // "Alias [%s] entry in key/trust store [%s] does not exist in the properties file [%s]. "
        // + "It is recommended that you manually correct this before proceeding", alias,
        // keyStoreLocation, propertyFileLocation));
        // }
        // }

        Enumeration<Object> propertyEnumeration = configFile.keys();
        while (propertyEnumeration.hasMoreElements()) {
            String property = (String) propertyEnumeration.nextElement();
            if (!keystore.containsAlias(property)) {
                isInSync = false;
                throw new PropFileAndKeystoreOutOfSyncException(String.format(
                        "Property [%s] entry in properties file [%s] does not exist in the key/trust store [%s]. "
                                + "It is recommended that you manually correct this before proceeding",
                        property, propertyFileLocation, keyStoreLocation));
            }
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw new PropFileAndKeystoreOutOfSyncException(
                String.format("File [%] not found", propertyFileLocation));
    } catch (IOException e) {
        e.printStackTrace();
        throw new PropFileAndKeystoreOutOfSyncException(
                String.format("File [%] cannot be loaded.", propertyFileLocation));
    } catch (KeyStoreException e) {
        e.printStackTrace();
        throw new PropFileAndKeystoreOutOfSyncException(String
                .format("Error verifying the contents inside the key/trust store [%].", keyStoreLocation));
    } catch (KeystoreInstantiationException e) {
        e.printStackTrace();
        throw new PropFileAndKeystoreOutOfSyncException(e.getMessage());
    }
    return isInSync;
}

From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java

/**
 * Instantiates the encryptor and digester using the configuration properties. If the properties
 * are not found, reasonable defaults are used.
 * /*from ww  w .j av a  2  s .c  om*/
 * @param provider
 *            The provider to use (ex. BC)
 * @param keyStore
 *            The keystore from which to load the secret encryption key
 * @param keyPassword
 *            The secret key password
 * @throws Exception
 */
private void configureEncryption(Provider provider, KeyStore keyStore, char[] keyPassword) throws Exception {
    SecretKey secretKey = null;

    if (!keyStore.containsAlias(SECRET_KEY_ALIAS)) {
        logger.debug("encryption key not found, generating new one");
        KeyGenerator keyGenerator = KeyGenerator.getInstance(encryptionConfig.getEncryptionAlgorithm(),
                provider);
        keyGenerator.init(encryptionConfig.getEncryptionKeyLength());
        secretKey = keyGenerator.generateKey();
        KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(secretKey);
        keyStore.setEntry(SECRET_KEY_ALIAS, entry, new KeyStore.PasswordProtection(keyPassword));
    } else {
        logger.debug("found encryption key in keystore");
        secretKey = (SecretKey) keyStore.getKey(SECRET_KEY_ALIAS, keyPassword);
    }

    /*
     * Now that we have a secret key, store it in the encryption settings so that we can use it
     * to encryption things client side.
     */
    encryptionConfig.setSecretKey(secretKey.getEncoded());

    encryptor = new KeyEncryptor();
    encryptor.setProvider(provider);
    encryptor.setKey(secretKey);
    encryptor.setFormat(Output.BASE64);

    digester = new Digester();
    digester.setProvider(provider);
    digester.setAlgorithm(encryptionConfig.getDigestAlgorithm());
    digester.setFormat(Output.BASE64);
}