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:com.owncloud.android.lib.common.network.NetworkUtils.java

public static void removeCertFromKnownServersStore(String alias, Context context)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {

    KeyStore knownServers = getKnownServersStore(context);
    if (knownServers.containsAlias(alias)) {
        knownServers.deleteEntry(alias);
    }/*from w  w  w .j  av  a  2s  . c  om*/
    FileOutputStream fos = null;
    try {
        fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE);
        knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
    } finally {
        fos.close();
    }
}

From source file:org.openanzo.rdf.utils.KeystoreUtils.java

/**
 * // w  w  w . j a  v  a2 s.  com
 * @param keyStoreFile
 * @param keystoreType
 * @param password
 * @param alias
 * @param cert
 * @throws AnzoException
 */
public static void addTrustedCert(String keyStoreFile, String keystoreType, String password, String alias,
        X509Certificate cert) throws AnzoException {
    try {
        KeyStore keyStore = KeyStore.getInstance(keystoreType);
        keyStore.load(new FileInputStream(keyStoreFile), password.toCharArray());

        if (keyStore.containsAlias(alias)) {
            keyStore.deleteEntry(alias);
        }
        keyStore.setCertificateEntry(alias, cert);

        writeStoreToFile(keyStoreFile, password, keyStore);

    } catch (Exception cce) {
        throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR, cce);
    }
}

From source file:Main.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private static KeyStore getKeyStore(Context context) {
    KeyStore keyStore = null;
    try {//from  ww  w  .  j ava  2  s  .c  o m
        keyStore = KeyStore.getInstance(KEY_PROVIDER);
        keyStore.load(null);

        if (!keyStore.containsAlias(KEY_ALIAS)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // for api level 23+
                generateNewKey();
            } else {
                // for api level 18 - 22
                generateNewKeyOld(context);
            }
        }

    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return keyStore;
}

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

/** 
  * Generate a public/private key pair.//from ww  w. j av  a2 s  . c o m
  *
  * @throws Exception
  */
public static void generateKeyPair(KeyStore keyStore, char[] storePass, String alias, char[] keyPass,
        String dname, String keyAlg, int validity) throws Exception {
    int keySize = 1024;
    if (keyStore.containsAlias(alias)) {
        MessageFormat messageformat = new MessageFormat("Key pair not generated, alias <alias> already exists");
        Object[] aobj = { alias };
        throw new Exception(messageformat.format(((Object) (aobj))));
    }

    String sigAlg = null;

    if (keyAlg.equalsIgnoreCase("DSA")) {
        sigAlg = "SHA1WithDSA";
    } else if (keyAlg.equalsIgnoreCase("RSA")) {
        sigAlg = "MD5WithRSA";
    } else {
        throw new Exception("Cannot derive signature algorithm");
    }

    //Must specify provider "SunRsaSign" otherwise it gets some weird NSS specific provider
    //when running in AppServer EE.
    CertAndKeyGen certandkeygen = new CertAndKeyGen(keyAlg, sigAlg);
    X500Name x500name;

    if (dname == null) {
        throw new Exception("Key pair not generated, dname is null.");
    } else {
        x500name = new X500Name(dname);
    }

    certandkeygen.generate(keySize);

    PrivateKey privatekey = certandkeygen.getPrivateKey();
    X509Certificate[] ax509certificate = new X509Certificate[1];
    ax509certificate[0] = certandkeygen.getSelfCertificate(x500name, validity * 24 * 60 * 60);

    keyStore.setKeyEntry(alias, privatekey, keyPass, ax509certificate);
}

From source file:org.wso2.carbon.identity.relyingparty.saml.X509CredentialUtil.java

/**
 * Creates the X509Credential from the TrustStore certificate.
 *//*ww  w  . j a  v a 2  s . c o m*/
public static X509Credential loadCredentialFromTrustStore(String alias, KeyStore trustStore)
        throws RelyingPartyException {
    X509Credential credential = null;
    java.security.cert.X509Certificate cert = null;

    try {
        if (trustStore.containsAlias(alias)) {
            cert = (java.security.cert.X509Certificate) trustStore.getCertificate(alias);
            credential = new X509CredentialImpl(cert);
        }
    } catch (KeyStoreException e) {
        log.error("Error while loading credentials from trust store", e);
        throw new RelyingPartyException("Error while loading credentials from trust store", e);
    }
    return credential;
}

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

private static void deleteKey(KeyStore keyStore, String keyName) {
    try {//www.  j ava2s  . c o m
        if (keyStore.containsAlias(keyName)) {
            keyStore.deleteEntry(keyName);
        }
    } catch (KeyStoreException e) {
        throw new PaxmlRuntimeException(e);
    }
}

From source file:org.wso2.carbon.identity.relyingparty.saml.IssuerCertificateUtil.java

/**
 * This method checks whether the certificate is present in the certificate store
 *//*from w  w  w  .  j a  va  2 s.co  m*/
public static boolean checkSystemStore(X509Certificate signedCert, KeyStore systemStore) throws Exception {
    if (signedCert == null || systemStore == null) {
        throw new RelyingPartyException("invalidInputParams");
    }

    // validity period
    signedCert.checkValidity();

    try {
        return systemStore.containsAlias(signedCert.getIssuerDN().getName());
    } catch (KeyStoreException e) {
        log.error("The keystore has not been initialized", e);
        throw new RelyingPartyException("errorLoadingTrustedKeystore", e);
    }
}

From source file:org.panlab.tgw.restclient.PtmInfoParser.java

private static void processCertificate(String alias, X509Certificate x509, URL url) {
    try {/*from   w w w .j a va  2s  . c  om*/
        String store = System.getProperty("javax.net.ssl.trustStore");
        String password = System.getProperty("javax.net.ssl.trustStorePassword");

        KeyStore keystore = KeyStore.getInstance("JKS");
        keystore.load(new FileInputStream(store), password.toCharArray());

        Enumeration<String> en = keystore.aliases();
        while (en.hasMoreElements()) {
            log.info(en.nextElement());
        }

        if (!keystore.containsAlias(alias)) {
            ByteArrayInputStream bais = new ByteArrayInputStream(x509.getEncoded());
            Certificate cert = CertificateFactory.getInstance("x509").generateCertificate(bais);
            keystore.setCertificateEntry(alias, cert);

            storeNewPTM(alias, url, x509.getSubjectDN().toString().replace(", ", ","));

            en = keystore.aliases();
            while (en.hasMoreElements()) {
                log.info(en.nextElement());
            }
            keystore.store(new FileOutputStream(store), password.toCharArray());

            TrustManagerFactory.getInstance("PKIX").init(keystore);
        }

    } catch (Exception error) {
        log.error(error.getMessage());
    }
}

From source file:org.sandrob.android.net.http.HttpsConnection.java

/**
 * Find an unused alias in the keystore based on the given alias.
 * // w ww . j  a v  a 2s .  c o  m
 * @param keyStore the keystore
 * @param alias the alias
 * @return alias that is not in use in the keystore
 * @throws KeyStoreException
 */
private static String findUnusedAlias(KeyStore keyStore, String alias) throws KeyStoreException {
    if (keyStore.containsAlias(alias)) {
        int i = 1;
        while (true) {
            String nextAlias = alias + " (" + i + ")";
            if (!keyStore.containsAlias(nextAlias)) {
                alias = nextAlias;
                break;
            }
        }
    }
    return alias;
}

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

public static KeyPair generate(File keystore) {
    if (keystore == null) {
        throw new IllegalArgumentException("Key Store file should not be null.");
    }// w w w. ja  va 2  s .com

    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)) {
            PrivateKey privateKey = (PrivateKey) ks.getKey(ALIAS, SECRET);
            PublicKey publicKey = ks.getCertificate(ALIAS).getPublicKey();
            return new KeyPair(publicKey, privateKey);
        } else {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(KEYSIZE, new SecureRandom());
            return generator.generateKeyPair();
        }
    } catch (Throwable th) {
        logger.error("Failed to initialize key store");
        throw new OpenFlameRuntimeException(th.getMessage(), th);
    }
}