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:Main.java

public static void main(String[] argv) throws Exception {
    FileInputStream is = new FileInputStream("yourfile" + ".keystore");
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    String password = "my-keystore-password";
    keystore.load(is, password.toCharArray());

    Enumeration e = keystore.aliases();
    for (; e.hasMoreElements();) {
        String alias = (String) e.nextElement();

        boolean b = keystore.isKeyEntry(alias);

        b = keystore.isCertificateEntry(alias);
    }// ww  w . j a v  a2 s. c  o m
    is.close();
}

From source file:PKCS12Import.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("usage: java PKCS12Import {pkcs12file} [newjksfile]");
        System.exit(1);//w  w w  .  j  av  a  2  s .  co  m
    }

    File fileIn = new File(args[0]);
    File fileOut;
    if (args.length > 1) {
        fileOut = new File(args[1]);
    } else {
        fileOut = new File("newstore.jks");
    }

    if (!fileIn.canRead()) {
        System.err.println("Unable to access input keystore: " + fileIn.getPath());
        System.exit(2);
    }

    if (fileOut.exists() && !fileOut.canWrite()) {
        System.err.println("Output file is not writable: " + fileOut.getPath());
        System.exit(2);
    }

    KeyStore kspkcs12 = KeyStore.getInstance("pkcs12");
    KeyStore ksjks = KeyStore.getInstance("jks");

    System.out.print("Enter input keystore passphrase: ");
    char[] inphrase = readPassphrase();
    System.out.print("Enter output keystore passphrase: ");
    char[] outphrase = readPassphrase();

    kspkcs12.load(new FileInputStream(fileIn), inphrase);

    ksjks.load((fileOut.exists()) ? new FileInputStream(fileOut) : null, outphrase);

    Enumeration eAliases = kspkcs12.aliases();
    int n = 0;
    while (eAliases.hasMoreElements()) {
        String strAlias = (String) eAliases.nextElement();
        System.err.println("Alias " + n++ + ": " + strAlias);

        if (kspkcs12.isKeyEntry(strAlias)) {
            System.err.println("Adding key for alias " + strAlias);
            Key key = kspkcs12.getKey(strAlias, inphrase);

            Certificate[] chain = kspkcs12.getCertificateChain(strAlias);

            ksjks.setKeyEntry(strAlias, key, outphrase, chain);
        }
    }

    OutputStream out = new FileOutputStream(fileOut);
    ksjks.store(out, outphrase);
    out.close();
}

From source file:createSod.java

/**
 * @param args//from  w  w w.j a  va  2  s. c o m
 * @throws CMSException 
 */
public static void main(String[] args) throws Exception {

    try {
        CommandLine options = verifyArgs(args);
        String privateKeyLocation = options.getOptionValue("privatekey");
        String keyPassword = options.getOptionValue("keypass");
        String certificate = options.getOptionValue("certificate");
        String sodContent = options.getOptionValue("content");
        String sod = "";
        if (options.hasOption("out")) {
            sod = options.getOptionValue("out");
        }

        // CHARGEMENT DU FICHIER PKCS#12

        KeyStore ks = null;
        char[] password = null;

        Security.addProvider(new BouncyCastleProvider());
        try {
            ks = KeyStore.getInstance("PKCS12");
            // Password pour le fichier personnal_nyal.p12
            password = keyPassword.toCharArray();
            ks.load(new FileInputStream(privateKeyLocation), password);
        } catch (Exception e) {
            System.out.println("Erreur: fichier " + privateKeyLocation
                    + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect");
            return;
        }

        // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE

        X509Certificate cert = null;
        PrivateKey privatekey = null;
        PublicKey publickey = null;

        try {
            Enumeration en = ks.aliases();
            String ALIAS = "";
            Vector vectaliases = new Vector();

            while (en.hasMoreElements())
                vectaliases.add(en.nextElement());
            String[] aliases = (String[]) (vectaliases.toArray(new String[0]));
            for (int i = 0; i < aliases.length; i++)
                if (ks.isKeyEntry(aliases[i])) {
                    ALIAS = aliases[i];
                    break;
                }
            privatekey = (PrivateKey) ks.getKey(ALIAS, password);
            cert = (X509Certificate) ks.getCertificate(ALIAS);
            publickey = ks.getCertificate(ALIAS).getPublicKey();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // Chargement du certificat  partir du fichier

        InputStream inStream = new FileInputStream(certificate);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(inStream);
        inStream.close();

        // Chargement du fichier qui va tre sign

        File file_to_sign = new File(sodContent);
        byte[] buffer = new byte[(int) file_to_sign.length()];
        DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign));
        in.readFully(buffer);
        in.close();

        // Chargement des certificats qui seront stocks dans le fichier .p7
        // Ici, seulement le certificat personnal_nyal.cer sera associ.
        // Par contre, la chane des certificats non.

        ArrayList certList = new ArrayList();
        certList.add(cert);
        CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                "BC");

        CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();

        // privatekey correspond  notre cl prive rcupre du fichier PKCS#12
        // cert correspond au certificat publique personnal_nyal.cer
        // Le dernier argument est l'algorithme de hachage qui sera utilis

        signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1);
        signGen.addCertificatesAndCRLs(certs);
        CMSProcessable content = new CMSProcessableByteArray(buffer);

        // Generation du fichier CMS/PKCS#7
        // L'argument deux permet de signifier si le document doit tre attach avec la signature
        //     Valeur true:  le fichier est attach (c'est le cas ici)
        //     Valeur false: le fichier est dtach

        CMSSignedData signedData = signGen.generate(content, true, "BC");
        byte[] signeddata = signedData.getEncoded();

        // Ecriture du buffer dans un fichier.   

        if (sod.equals("")) {
            System.out.print(signeddata.toString());
        } else {
            FileOutputStream envfos = new FileOutputStream(sod);
            envfos.write(signeddata);
            envfos.close();
        }

    } catch (OptionException oe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(NAME, getOptions());
        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

}

From source file:com.hhi.bigdata.platform.push.client.RegisterUtil.java

/**
 * <pre>//from w  w w  .  j ava 2 s .co  m
 * create a SSLSocketFactory instance with given parameters
 * </pre>
 * @param keystore
 * @param password
 * @return
 * @throws IOException
 */
private static PrivateKey getPrivateKey(KeyStore keystore, String password) throws Exception {
    Key key = null;

    // List the aliases
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = (String) aliases.nextElement();

        if (keystore.isKeyEntry(alias)) {
            key = keystore.getKey(alias, password.toCharArray());
        }
    }

    return (PrivateKey) key;
}

From source file:net.sf.keystore_explorer.crypto.keystore.KeyStoreUtil.java

/**
 * Is the named entry in the KeyStore a key pair entry?
 *
 * @param alias/*from w w w.  j av  a 2s .  c o m*/
 *            Alias
 * @param keyStore
 *            KeyStore
 * @return True if it is, false otherwise
 * @throws KeyStoreException
 *             If there was a problem accessing the KeyStore.
 */
public static boolean isKeyPairEntry(String alias, KeyStore keyStore) throws KeyStoreException {
    return keyStore.isKeyEntry(alias) && keyStore.getCertificateChain(alias) != null
            && keyStore.getCertificateChain(alias).length != 0;
}

From source file:net.sf.keystore_explorer.crypto.keystore.KeyStoreUtil.java

/**
 * Is the named entry in the KeyStore a key entry?
 *
 * @param alias/*w  w w  . j  a v a 2s  . co m*/
 *            Alias
 * @param keyStore
 *            KeyStore
 * @return True if it is, false otherwise
 * @throws KeyStoreException
 *             If there was a problem accessing the KeyStore.
 */
public static boolean isKeyEntry(String alias, KeyStore keyStore) throws KeyStoreException {
    return keyStore.isKeyEntry(alias)
            && (keyStore.getCertificateChain(alias) == null || keyStore.getCertificateChain(alias).length == 0);
}

From source file:org.commonjava.util.jhttpc.INTERNAL.util.SSLUtils.java

public static KeyStore readKeyAndCert(final String pemContent, final String keyPass)
        throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException,
        InvalidKeySpecException, JHttpCException {
    Logger logger = LoggerFactory.getLogger(SSLUtils.class);

    boolean bcEnabled = true;
    for (String bctestName : BC_TEST_NAMES) {
        try {//from  w  w  w  . ja  va  2s.c  o  m
            Class.forName(bctestName);
        } catch (ClassNotFoundException e) {
            logger.warn(
                    "One or more BouncyCastle jars (bcprov-jdk15on, bcpkix-jdk15on) are missing from the classpath! PEM SSL client keys are not supported!");
            bcEnabled = false;
            break;
        }
    }

    if (!bcEnabled) {
        return null;
    }

    KeyStore ks = BouncyCastleUtils.readKeyAndCertFromPem(pemContent, keyPass);

    Enumeration<String> aliases = ks.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        logger.trace("Got alias: {}. Is Cert? {} Is Private key? {}", alias, ks.isCertificateEntry(alias),
                ks.isKeyEntry(alias));
    }

    return ks;
}

From source file:org.apache.accumulo.test.util.CertUtils.java

static PrivateKey findPrivateKey(KeyStore keyStore, char[] keystorePassword)
        throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException {
    Enumeration<String> aliases = keyStore.aliases();
    PrivateKey key = null;//from  ww  w. ja  v  a2s  .c o  m
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keyStore.isKeyEntry(alias)) {
            if (key == null) {
                key = (PrivateKey) keyStore.getKey(alias, keystorePassword);
            } else {
                log.warn("Found multiple keys in keystore.  Ignoring " + alias);
            }
        }
    }
    if (key == null) {
        throw new KeyStoreException("Could not find private key in keystore");
    }
    return key;
}

From source file:mitm.common.tools.PfxTool.java

private static void printKeystoreDetails(KeyStore keyStore) throws KeyStoreException {
    Enumeration<String> aliases = keyStore.aliases();

    int count = 0;

    System.out.println("**** BEGIN ENTRIES ***");

    while (aliases.hasMoreElements()) {
        count++;/* w w w .j  av a  2 s .  c om*/

        String alias = aliases.nextElement();

        StrBuilder sb = new StrBuilder();

        sb.append("Alias: ").append(alias).append(", key entry: ").append(keyStore.isKeyEntry(alias));

        System.out.println(sb.toString());
    }

    System.out.println("**** END ENTRIES ***");
    System.out.println("Nr of entries: " + count);
}

From source file:org.teknux.jettybootstrap.keystore.JettyKeystoreConvertorBuilder.java

private static PrivateKeyEntry getPrivateKeyEntryOfKeyStore(KeyStore keystore, String password, String alias)
        throws JettyKeystoreException {
    try {/*from w w w. j av  a  2  s.c o m*/
        if (alias == null) {
            Enumeration<String> aliasEnumeration = keystore.aliases();

            while (aliasEnumeration.hasMoreElements()) {
                String aliasItem = aliasEnumeration.nextElement();

                if (keystore.isKeyEntry(aliasItem)) {
                    Entry entry = keystore.getEntry(aliasItem,
                            new KeyStore.PasswordProtection(password.toCharArray()));

                    if (entry instanceof PrivateKeyEntry) {
                        return (PrivateKeyEntry) entry;
                    }
                }
            }

        } else {
            Entry entry = keystore.getEntry(alias, new KeyStore.PasswordProtection(password.toCharArray()));

            if (entry instanceof PrivateKeyEntry) {
                return (PrivateKeyEntry) entry;
            }
        }

        throw new JettyKeystoreException(JettyKeystoreException.ERROR_UNREACHABLE_PRIVATE_KEY_ENTRY,
                "Can not find private key entry");
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableEntryException e) {
        throw new JettyKeystoreException(JettyKeystoreException.ERROR_UNREACHABLE_PRIVATE_KEY_ENTRY,
                "Can not find private key entry", e);
    }
}