Java Code Examples for java.security.KeyStore.isKeyEntry()

The following are Jave code examples for showing how to use isKeyEntry() of the java.security.KeyStore class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: xitk   File: P12CertExportCmd.java   View Source Code Vote up 6 votes
@Override
protected Object execute0() throws Exception {
    KeyStore ks = getKeyStore();

    String keyname = null;
    Enumeration<String> aliases = ks.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (ks.isKeyEntry(alias)) {
            keyname = alias;
            break;
        }
    }

    if (keyname == null) {
        throw new CmdFailure("could not find private key");
    }

    X509Certificate cert = (X509Certificate) ks.getCertificate(keyname);
    saveVerbose("saved certificate to file", new File(outFile), cert.getEncoded());

    return null;
}
 
Example 2
Project: aos-FileCoreLibrary   File: KeyManagerUtils.java   View Source Code Vote up 5 votes
private static String findAlias(KeyStore ks) throws KeyStoreException {
    Enumeration<String> e = ks.aliases();
    while(e.hasMoreElements()) {
        String entry = e.nextElement();
        if (ks.isKeyEntry(entry)) {
            return entry;
        }
    }
    throw new KeyStoreException("Cannot find a private key entry");
}
 
Example 3
Project: tomcat7   File: JSSESocketFactory.java   View Source Code Vote up 5 votes
/**
 * Gets the initialized key managers.
 */
protected KeyManager[] getKeyManagers(String keystoreType,
                                      String keystoreProvider,
                                      String algorithm,
                                      String keyAlias)
            throws Exception {

    KeyManager[] kms = null;

    String keystorePass = getKeystorePassword();

    KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass);
    if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
        throw new IOException(
                sm.getString("jsse.alias_no_key_entry", keyAlias));
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
    String keyPass = endpoint.getKeyPass();
    if (keyPass == null) {
        keyPass = keystorePass;
    }
    kmf.init(ks, keyPass.toCharArray());

    kms = kmf.getKeyManagers();
    if (keyAlias != null) {
        String alias = keyAlias;
        if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) {
            alias = alias.toLowerCase(Locale.ENGLISH);
        }
        for(int i=0; i<kms.length; i++) {
            kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], alias);
        }
    }

    return kms;
}
 
Example 4
Project: xitk   File: SoftTokenMacContentSignerBuilder.java   View Source Code Vote up 5 votes
public SoftTokenMacContentSignerBuilder(String keystoreType, InputStream keystoreStream,
        char[] keystorePassword, String keyname, char[] keyPassword)
        throws XiSecurityException {
    if (!"JCEKS".equalsIgnoreCase(keystoreType)) {
        throw new IllegalArgumentException("unsupported keystore type: " + keystoreType);
    }
    ParamUtil.requireNonNull("keystoreStream", keystoreStream);
    ParamUtil.requireNonNull("keystorePassword", keystorePassword);
    ParamUtil.requireNonNull("keyPassword", keyPassword);

    try {
        KeyStore ks = KeyUtil.getKeyStore(keystoreType);
        ks.load(keystoreStream, keystorePassword);

        String tmpKeyname = keyname;
        if (tmpKeyname == null) {
            Enumeration<String> aliases = ks.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                if (ks.isKeyEntry(alias)) {
                    tmpKeyname = alias;
                    break;
                }
            }
        } else {
            if (!ks.isKeyEntry(tmpKeyname)) {
                throw new XiSecurityException("unknown key named " + tmpKeyname);
            }
        }

        this.key = (SecretKey) ks.getKey(tmpKeyname, keyPassword);
    } catch (KeyStoreException | NoSuchProviderException | NoSuchAlgorithmException
            | CertificateException | IOException | UnrecoverableKeyException
            | ClassCastException ex) {
        throw new XiSecurityException(ex.getMessage(), ex);
    }
}
 
Example 5
Project: xitk   File: P12CertUpdateCmd.java   View Source Code Vote up 5 votes
@Override
protected Object execute0() throws Exception {
    KeyStore ks = getKeyStore();

    char[] pwd = getPassword();
    X509Certificate newCert = X509Util.parseCert(certFile);

    assertMatch(newCert, new String(pwd));

    String keyname = null;
    Enumeration<String> aliases = ks.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (ks.isKeyEntry(alias)) {
            keyname = alias;
            break;
        }
    }

    if (keyname == null) {
        throw new XiSecurityException("could not find private key");
    }

    Key key = ks.getKey(keyname, pwd);
    Set<X509Certificate> caCerts = new HashSet<>();
    if (isNotEmpty(caCertFiles)) {
        for (String caCertFile : caCertFiles) {
            caCerts.add(X509Util.parseCert(caCertFile));
        }
    }
    X509Certificate[] certChain = X509Util.buildCertPath(newCert, caCerts);
    ks.setKeyEntry(keyname, key, pwd, certChain);

    try (FileOutputStream out = new FileOutputStream(p12File)) {
        ks.store(out, pwd);
        println("updated certificate");
        return null;
    }
}
 
Example 6
Project: xitk   File: ConvertKeystoreCmd.java   View Source Code Vote up 5 votes
@Override
protected Object execute0() throws Exception {
    File realInFile = new File(IoUtil.expandFilepath(inFile));
    File realOutFile = new File(IoUtil.expandFilepath(outFile));

    if (CompareUtil.equalsObject(realInFile, realOutFile)) {
        throw new IllegalCmdParamException("in and out cannot be the same");
    }

    KeyStore inKs = KeyStore.getInstance(inType);
    KeyStore outKs = KeyStore.getInstance(outType);
    outKs.load(null);

    char[] inPassword = readPasswordIfNotSet("password of the source keystore", inPwd);
    FileInputStream inStream = new FileInputStream(realInFile);
    try {
        inKs.load(inStream, inPassword);
    } finally {
        inStream.close();
    }

    char[] outPassword = readPasswordIfNotSet("password of the destination keystore", outPwd);
    Enumeration<String> aliases = inKs.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (inKs.isKeyEntry(alias)) {
            Certificate[] certs = inKs.getCertificateChain(alias);
            Key key = inKs.getKey(alias, inPassword);
            outKs.setKeyEntry(alias, key, outPassword, certs);
        } else {
            Certificate cert = inKs.getCertificate(alias);
            outKs.setCertificateEntry(alias, cert);
        }
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
    outKs.store(bout, outPassword);
    saveVerbose("saved destination keystore to file", realOutFile, bout.toByteArray());
    return null;
}
 
Example 7
Project: lams   File: JSSESocketFactory.java   View Source Code Vote up 5 votes
/**
 * Gets the initialized key managers.
 */
protected KeyManager[] getKeyManagers(String keystoreType,
                                      String keystoreProvider,
                                      String algorithm,
                                      String keyAlias)
            throws Exception {

    KeyManager[] kms = null;

    KeyStore ks = getKeystore(keystoreType, keystoreProvider, listener.getSslKeyStorePass());
    if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
        throw new IOException(sm.getString("jsse.alias_no_key_entry", keyAlias));
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
    kmf.init(ks, listener.getSslKeyStorePass().toCharArray());

    kms = kmf.getKeyManagers();
    if (keyAlias != null) {
        if ("JKS".equals(keystoreType)) {
            keyAlias = keyAlias.toLowerCase();
        }
        for(int i=0; i<kms.length; i++) {
            kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], keyAlias);
        }
    }

    return kms;
}
 
Example 8
Project: java-coap   File: DeviceEmulator.java   View Source Code Vote up 5 votes
static SSLContext sslContextFromKeystore(String resource, char[] secret) {
    try {
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(resource), secret);

        final KeyManagerFactory kmf;
        kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, secret);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(ks);

        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        //print all certificates subject
        Enumeration<String> aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            String certCN = ((X509Certificate) ks.getCertificate(alias)).getSubjectDN().toString();

            if (ks.isKeyEntry(alias)) {
                LOGGER.info("Using certificate CN: " + certCN);
            } else {
                LOGGER.info("Using trusted certificate CN: " + certCN);
            }
        }

        return sslContext;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 9
Project: openjdk-jdk10   File: ConvertP12Test.java   View Source Code Vote up 5 votes
private void run(KeyStore inputKeyStore, KeyStore outputKeyStore,
        String inKeyPass, String outKeyPass) throws Exception {
    Enumeration<String> e = inputKeyStore.aliases();
    String alias;
    while (e.hasMoreElements()) {
        alias = e.nextElement();
        Certificate[] certs = inputKeyStore.getCertificateChain(alias);

        boolean isCertEntry = inputKeyStore.isCertificateEntry(alias);
        // Test KeyStore only contain key pair entries.
        if (isCertEntry == true) {
            throw new RuntimeException(
                    "inputKeystore should not be certEntry because test"
                            + " keystore only contain key pair entries"
                            + " for alias:" + alias);
        }

        boolean isKeyEntry = inputKeyStore.isKeyEntry(alias);
        Key key = null;
        if (isKeyEntry) {
            key = inputKeyStore.getKey(alias, inKeyPass.toCharArray());
        } else {
            throw new RuntimeException("Entry type unknown for alias:"
                    + alias);
        }
        outputKeyStore.setKeyEntry(alias, key, outKeyPass.toCharArray(),
                certs);
    }
}
 
Example 10
Project: jdk8u-jdk   File: ConvertP12Test.java   View Source Code Vote up 5 votes
private void run(KeyStore inputKeyStore, KeyStore outputKeyStore,
        String inKeyPass, String outKeyPass) throws Exception {
    Enumeration<String> e = inputKeyStore.aliases();
    String alias;
    while (e.hasMoreElements()) {
        alias = e.nextElement();
        Certificate[] certs = inputKeyStore.getCertificateChain(alias);

        boolean isCertEntry = inputKeyStore.isCertificateEntry(alias);
        // Test KeyStore only contain key pair entries.
        if (isCertEntry == true) {
            throw new RuntimeException(
                    "inputKeystore should not be certEntry because test"
                            + " keystore only contain key pair entries"
                            + " for alias:" + alias);
        }

        boolean isKeyEntry = inputKeyStore.isKeyEntry(alias);
        Key key = null;
        if (isKeyEntry) {
            key = inputKeyStore.getKey(alias, inKeyPass.toCharArray());
        } else {
            throw new RuntimeException("Entry type unknown for alias:"
                    + alias);
        }
        outputKeyStore.setKeyEntry(alias, key, outKeyPass.toCharArray(),
                certs);
    }
}
 
Example 11
Project: lazycat   File: JSSESocketFactory.java   View Source Code Vote up 5 votes
/**
 * Gets the initialized key managers.
 */
protected KeyManager[] getKeyManagers(String keystoreType, String keystoreProvider, String algorithm,
		String keyAlias) throws Exception {

	KeyManager[] kms = null;

	String keystorePass = getKeystorePassword();

	KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass);
	if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
		throw new IOException(sm.getString("jsse.alias_no_key_entry", keyAlias));
	}

	KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
	String keyPass = endpoint.getKeyPass();
	if (keyPass == null) {
		keyPass = keystorePass;
	}
	kmf.init(ks, keyPass.toCharArray());

	kms = kmf.getKeyManagers();
	if (keyAlias != null) {
		String alias = keyAlias;
		if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) {
			alias = alias.toLowerCase(Locale.ENGLISH);
		}
		for (int i = 0; i < kms.length; i++) {
			kms[i] = new JSSEKeyManager((X509KeyManager) kms[i], alias);
		}
	}

	return kms;
}
 
Example 12
Project: easyssl   File: SSLContextCreator.java   View Source Code Vote up 5 votes
private static String getKeyAlias(SSLConfig config,KeyStore ks)throws Exception{
  
	  String keyAlias = config.getKeyAlias();
	  if(keyAlias != null){
		  if(!ks.isKeyEntry(keyAlias)){
			  throw new IllegalArgumentException(keyAlias + " is not a key entry.");
		  }  	  
	  }else{
		  keyAlias = getFirstKeyEntryAlias(ks);
		  if(keyAlias == null){
			  throw new IllegalArgumentException("There is no key entry in key store " + config.getKeystoreFile());
		  }
	  }
	  return keyAlias;
}
 
Example 13
Project: easyssl   File: SSLContextCreator.java   View Source Code Vote up 5 votes
private static String getFirstKeyEntryAlias(KeyStore ks)throws Exception{
	  
	  Enumeration<String> e = ks.aliases();
	  while(e.hasMoreElements()){
		  String alias = e.nextElement();
		  if(ks.isKeyEntry(alias)){
			  return alias;
		  }
	  }
	  return null;
}
 
Example 14
Project: ats-framework   File: SslUtils.java   View Source Code Vote up 4 votes
private static void createKeyStoreFromPemKey(
                                              String clientCert,
                                              String clientPass,
                                              KeyStore store ) throws Exception {

    try {
        // Load CA Chain file
        // CertificateFactory cf = CertificateFactory.getInstance("X.509");
        // X509Certificate cert = (X509Certificate) cf.generateCertificate(new FileInputStream(caCert));
        store.load(null);

        // Load client's public and private keys from PKCS12 certificate
        KeyStore inputKeyStore = KeyStore.getInstance("PKCS12");
        FileInputStream fis = new FileInputStream(clientCert);
        char[] nPassword = null;
        if ( (clientPass == null) || "".equals(clientPass.trim())) {
            nPassword = null;
        } else {
            nPassword = clientPass.toCharArray();
        }
        inputKeyStore.load(fis, nPassword);
        fis.close();
        store.load(null, ( (clientPass != null)
                                                ? clientPass.toCharArray()
                                                : null));
        Enumeration<String> en = inputKeyStore.aliases();
        while (en.hasMoreElements()) { // we are reading just one certificate.
            String keyAlias = en.nextElement();
            if (inputKeyStore.isKeyEntry(keyAlias)) {
                Key key = inputKeyStore.getKey(keyAlias, nPassword);
                Certificate[] certChain = inputKeyStore.getCertificateChain(keyAlias);
                store.setKeyEntry("outkey",
                                  key,
                                  ( (clientPass != null)
                                                         ? clientPass.toCharArray()
                                                         : null),
                                  certChain);
            }
        }

    } catch (Exception e) {
        throw new RuntimeException("Error creating keystore from Pem key", e);
    }
}
 
Example 15
Project: xitk   File: P11SecretKeyCreateCmd.java   View Source Code Vote up 4 votes
@Override
protected Object execute0() throws Exception {
    long p11KeyType;
    if ("AES".equalsIgnoreCase(keyType)) {
        p11KeyType = PKCS11Constants.CKK_AES;

    } else if ("DES3".equalsIgnoreCase(keyType)) {
        p11KeyType = PKCS11Constants.CKK_DES3;
    } else if ("GENERIC".equalsIgnoreCase(keyType)) {
        p11KeyType = PKCS11Constants.CKK_GENERIC_SECRET;
    } else {
        throw new IllegalCmdParamException("invalid keyType " + keyType);
    }

    KeyStore ks = KeyStore.getInstance("JCEKS");
    InputStream ksStream = new FileInputStream(IoUtil.expandFilepath(keyOutFile));
    char[] pwd = getPassword();
    try {
        ks.load(ksStream, pwd);
    } finally {
        ksStream.close();
    }

    byte[] keyValue = null;
    Enumeration<String> aliases = ks.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (!ks.isKeyEntry(alias)) {
            continue;
        }

        Key key = ks.getKey(alias, pwd);
        if (key instanceof SecretKey) {
            keyValue = ((SecretKey) key).getEncoded();
            break;
        }
    }

    if (keyValue == null) {
        throw new IllegalCmdParamException("keystore does not contain secret key");
    }

    P11Slot slot = getSlot();
    P11ObjectIdentifier objId = slot.createSecretKey(p11KeyType, keyValue, label,
            getControl());
    finalize("Create Secret Key", objId);
    return null;
}
 
Example 16
Project: openjdk-jdk10   File: TestKeyStoreEntry.java   View Source Code Vote up 4 votes
public void runTest(Provider p) throws Exception {
    try (FileOutputStream fos = new FileOutputStream("jceks");
            FileInputStream fis = new FileInputStream("jceks");) {

        KeyStore ks = KeyStore.getInstance("jceks", p);
        // create an empty key store
        ks.load(null, null);

        // store the secret keys
        String aliasHead = new String("secretKey");
        for (int j = 0; j < NUM_ALGOS; j++) {
            ks.setKeyEntry(aliasHead + j, sks[j], PASSWDK, null);
        }

        // write the key store out to a file
        ks.store(fos, PASSWDF);
        // wipe clean the existing key store
        for (int k = 0; k < NUM_ALGOS; k++) {
            ks.deleteEntry(aliasHead + k);
        }
        if (ks.size() != 0) {
            throw new RuntimeException("ERROR: re-initialization failed");
        }

        // reload the key store with the file
        ks.load(fis, PASSWDF);

        // check the integrity/validaty of the key store
        Key temp = null;
        String alias = null;
        if (ks.size() != NUM_ALGOS) {
            throw new RuntimeException("ERROR: wrong number of key"
                    + " entries");
        }

        for (int m = 0; m < ks.size(); m++) {
            alias = aliasHead + m;
            temp = ks.getKey(alias, PASSWDK);
            // compare the keys
            if (!temp.equals(sks[m])) {
                throw new RuntimeException("ERROR: key comparison (" + m
                        + ") failed");
            }
            // check the type of key
            if (ks.isCertificateEntry(alias) || !ks.isKeyEntry(alias)) {
                throw new RuntimeException("ERROR: type identification ("
                        + m + ") failed");
            }
        }
    }
}
 
Example 17
Project: jdk8u-jdk   File: WriteP12Test.java   View Source Code Vote up 4 votes
private void testKeyStore(KeyStore inputKeyStore, char[] keypass)
        throws KeyStoreException, UnrecoverableKeyException,
        NoSuchAlgorithmException {
    out.println("========== Key Store ==========");
    out.println("getProvider : " + inputKeyStore.getProvider());
    out.println("getType : " + inputKeyStore.getType());
    out.println("getDefaultType : " + KeyStore.getDefaultType());

    int idx = 0;
    Enumeration<String> e = inputKeyStore.aliases();
    String alias;
    while (e.hasMoreElements()) {
        alias = e.nextElement();
        if (!inputKeyStore.containsAlias(alias)) {
            throw new RuntimeException("Alias not found");
        }
        out.println("Alias " + idx + " : " + alias);
        out.println("getCreationDate : "
                + inputKeyStore.getCreationDate(alias));
        X509Certificate cert = (X509Certificate) inputKeyStore
                .getCertificate(alias);
        out.println("getCertificate : " + cert.getSubjectDN());
        String retAlias = inputKeyStore.getCertificateAlias(cert);
        if (!retAlias.equals(alias)) {
            throw new RuntimeException("Alias mismatch, actually "
                    + retAlias + ", expected " + alias);
        }
        out.println("getCertificateAlias : " + retAlias);
        Certificate[] certs = inputKeyStore.getCertificateChain(alias);
        int i = 0;
        for (Certificate certification : certs) {
            out.println("getCertificateChain " + i
                    + ((X509Certificate) certification).getSubjectDN());
            i++;
        }
        if (inputKeyStore.isCertificateEntry(alias)) {
            throw new RuntimeException(
                    "inputKeystore should not be certEntry because this"
                            + " keystore only contain key pair entries.");
        }
        if (!inputKeyStore.isKeyEntry(alias)) {
            throw new RuntimeException("Entry type unknown.");
        }
        idx++;
    }
    int size = inputKeyStore.size();
    if (idx != size) {
        throw new RuntimeException("Size not match, actually " + idx
                + ", expected " + size);
    }
}
 
Example 18
Project: jdk8u-jdk   File: ReadP12Test.java   View Source Code Vote up 4 votes
private void readTest(String inKeyStore) throws Exception {

        KeyStore inputKeyStore;

        // Initialize KeyStore
        String dir = System.getProperty("test.src", ".");
        String keystorePath = dir + File.separator + "certs" + File.separator
                + "readP12";
        inputKeyStore = KeyStore
                .getInstance(IN_KETYSTORE_TYPE, IN_KEYSTORE_PRV);
        // KeyStore have encoded by Base64.getMimeEncoder().encode(),need decode
        // first.
        byte[] input = Files.readAllBytes(Paths.get(keystorePath, inKeyStore));
        ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64
                .getMimeDecoder().decode(input));
        inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray());
        out.println("Initialize KeyStore : " + inKeyStore + " success");

        out.println("getProvider : " + inputKeyStore.getProvider());
        out.println("getType : " + inputKeyStore.getType());
        out.println("getDefaultType : " + KeyStore.getDefaultType());

        int idx = 0;
        Enumeration<String> e = inputKeyStore.aliases();
        String alias;
        while (e.hasMoreElements()) {
            alias = e.nextElement();
            out.println("Alias " + idx + " : " + alias);
            if (inputKeyStore.containsAlias(alias) == false) {
                throw new RuntimeException("Alias not found");
            }

            out.println("getCreationDate : "
                    + inputKeyStore.getCreationDate(alias));

            X509Certificate cert = (X509Certificate) inputKeyStore
                    .getCertificate(alias);
            out.println("getCertificate : " + cert.getSubjectDN());
            String retAlias = inputKeyStore.getCertificateAlias(cert);
            if (!retAlias.equals(alias)) {
                throw new RuntimeException("Alias mismatch");
            }
            out.println("getCertificateAlias : " + retAlias);

            Certificate[] certs = inputKeyStore.getCertificateChain(alias);
            for (int i = 0; i < certs.length; i++) {
                out.println("getCertificateChain " + i + " : "
                        + ((X509Certificate) certs[i]).getSubjectDN());
            }

            boolean isCertEntry = inputKeyStore.isCertificateEntry(alias);
            // test KeyStore only contain key pair entries.
            if (isCertEntry == true) {
                throw new RuntimeException(
                        "inputKeystore should not be certEntry because test keystore only contain key pair entries.");
            }

            boolean isKeyEntry = inputKeyStore.isKeyEntry(alias);
            if (isKeyEntry) {
                Key key = inputKeyStore.getKey(alias,
                        IN_STORE_PASS.toCharArray());
                out.println("Key : " + key.toString());
            } else {
                throw new RuntimeException("Entry type unknown\n");
            }
            idx++;
        }

        int size = inputKeyStore.size();
        if (idx != size) {
            throw new RuntimeException("Size not match");
        }

    }
 
Example 19
Project: openjdk-jdk10   File: WriteP12Test.java   View Source Code Vote up 4 votes
private void testKeyStore(KeyStore inputKeyStore, char[] keypass)
        throws KeyStoreException, UnrecoverableKeyException,
        NoSuchAlgorithmException {
    out.println("========== Key Store ==========");
    out.println("getProvider : " + inputKeyStore.getProvider());
    out.println("getType : " + inputKeyStore.getType());
    out.println("getDefaultType : " + KeyStore.getDefaultType());

    int idx = 0;
    Enumeration<String> e = inputKeyStore.aliases();
    String alias;
    while (e.hasMoreElements()) {
        alias = e.nextElement();
        if (!inputKeyStore.containsAlias(alias)) {
            throw new RuntimeException("Alias not found");
        }
        out.println("Alias " + idx + " : " + alias);
        out.println("getCreationDate : "
                + inputKeyStore.getCreationDate(alias));
        X509Certificate cert = (X509Certificate) inputKeyStore
                .getCertificate(alias);
        out.println("getCertificate : " + cert.getSubjectDN());
        String retAlias = inputKeyStore.getCertificateAlias(cert);
        if (!retAlias.equals(alias)) {
            throw new RuntimeException("Alias mismatch, actually "
                    + retAlias + ", expected " + alias);
        }
        out.println("getCertificateAlias : " + retAlias);
        Certificate[] certs = inputKeyStore.getCertificateChain(alias);
        int i = 0;
        for (Certificate certification : certs) {
            out.println("getCertificateChain " + i
                    + ((X509Certificate) certification).getSubjectDN());
            i++;
        }
        if (inputKeyStore.isCertificateEntry(alias)) {
            throw new RuntimeException(
                    "inputKeystore should not be certEntry because this"
                            + " keystore only contain key pair entries.");
        }
        if (!inputKeyStore.isKeyEntry(alias)) {
            throw new RuntimeException("Entry type unknown.");
        }
        idx++;
    }
    int size = inputKeyStore.size();
    if (idx != size) {
        throw new RuntimeException("Size not match, actually " + idx
                + ", expected " + size);
    }
}
 
Example 20
Project: openjdk-jdk10   File: ReadP12Test.java   View Source Code Vote up 4 votes
private void readTest(String inKeyStore) throws Exception {

        KeyStore inputKeyStore;

        // Initialize KeyStore
        String dir = System.getProperty("test.src", ".");
        String keystorePath = dir + File.separator + "certs" + File.separator
                + "readP12";
        inputKeyStore = KeyStore.getInstance(IN_KEYSTORE_TYPE);
        // KeyStore have encoded by Base64.getMimeEncoder().encode(),need decode
        // first.
        byte[] input = Files.readAllBytes(Paths.get(keystorePath, inKeyStore));
        ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64
                .getMimeDecoder().decode(input));
        inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray());
        out.println("Initialize KeyStore : " + inKeyStore + " success");

        out.println("getProvider : " + inputKeyStore.getProvider());
        out.println("getType : " + inputKeyStore.getType());
        out.println("getDefaultType : " + KeyStore.getDefaultType());

        int idx = 0;
        Enumeration<String> e = inputKeyStore.aliases();
        String alias;
        while (e.hasMoreElements()) {
            alias = e.nextElement();
            out.println("Alias " + idx + " : " + alias);
            if (inputKeyStore.containsAlias(alias) == false) {
                throw new RuntimeException("Alias not found");
            }

            out.println("getCreationDate : "
                    + inputKeyStore.getCreationDate(alias));

            X509Certificate cert = (X509Certificate) inputKeyStore
                    .getCertificate(alias);
            out.println("getCertificate : " + cert.getSubjectDN());
            String retAlias = inputKeyStore.getCertificateAlias(cert);
            if (!retAlias.equals(alias)) {
                throw new RuntimeException("Alias mismatch");
            }
            out.println("getCertificateAlias : " + retAlias);

            Certificate[] certs = inputKeyStore.getCertificateChain(alias);
            for (int i = 0; i < certs.length; i++) {
                out.println("getCertificateChain " + i + " : "
                        + ((X509Certificate) certs[i]).getSubjectDN());
            }

            boolean isCertEntry = inputKeyStore.isCertificateEntry(alias);
            // test KeyStore only contain key pair entries.
            if (isCertEntry == true) {
                throw new RuntimeException(
                        "inputKeystore should not be certEntry because test keystore only contain key pair entries.");
            }

            boolean isKeyEntry = inputKeyStore.isKeyEntry(alias);
            if (isKeyEntry) {
                Key key = inputKeyStore.getKey(alias,
                        IN_STORE_PASS.toCharArray());
                out.println("Key : " + key.toString());
            } else {
                throw new RuntimeException("Entry type unknown\n");
            }
            idx++;
        }

        int size = inputKeyStore.size();
        if (idx != size) {
            throw new RuntimeException("Size not match");
        }

    }