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

The following are Jave code examples for showing how to use getCertificateChain() 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: openjdk-jdk10   File: GetPrivateKey.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws Exception {
    if (initSecmod() == false) {
        return;
    }

    String configName = BASE + SEP + "nss.cfg";
    Provider p = getSunPKCS11(configName);

    System.out.println(p);
    Security.addProvider(p);

    if (args.length > 1 && "sm".equals(args[0])) {
        System.setProperty("java.security.policy",
                BASE + File.separator + args[1]);
        System.setSecurityManager(new SecurityManager());
    }

    KeyStore ks = KeyStore.getInstance(PKCS11, p);
    ks.load(null, password);
    Collection<String> aliases = new TreeSet<>(
            Collections.list(ks.aliases()));
    System.out.println("entries: " + aliases.size());
    System.out.println(aliases);

    PrivateKey privateKey = (PrivateKey)ks.getKey(keyAlias, password);
    System.out.println(privateKey);

    byte[] data = generateData(1024);

    System.out.println("Signing...");
    Signature signature = Signature.getInstance("MD5withRSA");
    signature.initSign(privateKey);
    signature.update(data);
    byte[] sig = signature.sign();

    X509Certificate[] chain =
            (X509Certificate[]) ks.getCertificateChain(keyAlias);
    signature.initVerify(chain[0].getPublicKey());
    signature.update(data);
    boolean ok = signature.verify(sig);
    if (ok == false) {
        throw new Exception("Signature verification error");
    }

    System.out.println("OK");

}
 
Example 2
Project: RISE-V2G   File: SecurityUtils.java   View Source Code Vote up 6 votes
/**
 * Returns the mobility operator Sub-CA 2 certificate (MOSubCA2 certificate) which can verify the signature of the  
 * contract certificate from the given keystore. The public key of the MOSub2Certificate is then used to verify 
 * the signature of sales tariffs.
 * 
 * @param keyStoreFileName The relative path and file name of the keystore
 * @return The X.509 mobility operator Sub-CA2 certificate (a certificate from a Sub-CA)
 */
public static X509Certificate getMOSubCA2Certificate(String keyStoreFileName) {
	KeyStore keystore = getKeyStore(keyStoreFileName, GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString());
	X509Certificate moSubCA2Certificate = null;
	
	try {
		Certificate[] certChain = keystore.getCertificateChain(GlobalValues.ALIAS_CONTRACT_CERTIFICATE.toString());
		X509Certificate contractCertificate = getLeafCertificate(certChain);
		SubCertificatesType subCertificates = getSubCertificates(certChain); 
		
		for (byte[] certificate : subCertificates.getCertificate()) {
			X509Certificate x509Cert = getCertificate(certificate);
			if (contractCertificate.getIssuerX500Principal().getName().equals(
				x509Cert.getSubjectX500Principal().getName())) {
				moSubCA2Certificate = x509Cert;
				break;
			}
		}
	} catch (KeyStoreException e) {
		getLogger().error("KeyStoreException occurred while trying to get MOSubCA2 certificate");
	}
	
	return moSubCA2Certificate;
}
 
Example 3
Project: jdk8u-jdk   File: ConvertP12Test.java   View Source Code Vote up 6 votes
private void compareKeyEntry(KeyStore a, KeyStore b, String aPass,
        String bPass, String alias) throws KeyStoreException,
        UnrecoverableKeyException, NoSuchAlgorithmException {
    Certificate[] certsA = a.getCertificateChain(alias);
    Certificate[] certsB = b.getCertificateChain(alias);

    if (!Arrays.equals(certsA, certsB)) {
        throw new RuntimeException("Certs don't match for alias:" + alias);
    }

    Key keyA = a.getKey(alias, aPass.toCharArray());
    Key keyB = b.getKey(alias, bPass.toCharArray());

    if (!keyA.equals(keyB)) {
        throw new RuntimeException(
                "Key don't match for alias:" + alias);
    }
}
 
Example 4
Project: incubator-netbeans   File: Utilities.java   View Source Code Vote up 5 votes
public static Collection<Certificate> getCertificates (KeyStore keyStore) throws KeyStoreException {
    Set<Certificate> certs = new HashSet<Certificate> ();
    for (String alias: Collections.list (keyStore.aliases ())) {
        Certificate[] certificateChain = keyStore.getCertificateChain(alias);
        if (certificateChain != null) {
            certs.addAll(Arrays.asList(certificateChain));
        }
        certs.add(keyStore.getCertificate(alias));
    }
    return certs;
}
 
Example 5
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 6
Project: RISE-V2G   File: SecurityUtils.java   View Source Code Vote up 5 votes
/**
 * Returns the certificate chain from a PKCS#12 container holding credentials such as private key,
 * leaf certificate and zero or more intermediate certificates.
 * 
 * @param pkcs12Resource The PKCS#12 container
 * @return The certificate chain
 */
public static CertificateChainType getCertificateChain(String pkcs12Resource) {
	CertificateChainType certChain = new CertificateChainType();
	
	/*
	 * For testing purposes, the respective PKCS12 container file has already been put in the 
	 * resources folder. However, when implementing a real interface to a secondary actor's backend, 
	 * the retrieval of a certificate must be done via some other online mechanism.
	 */
	KeyStore contractCertificateKeystore = getPKCS12KeyStore(pkcs12Resource, GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString());
	
	if (contractCertificateKeystore == null) {
		getLogger().error("Unable to access certificate chain because no PKCS#12 container found at " +
						  "location '" + pkcs12Resource + "'");
		return null;
	}
	
	try {
		Enumeration<String> aliases = contractCertificateKeystore.aliases();
		Certificate[] tempCertChain = null;
		// Only one certificate chain (and therefore alias) should be available
		while (aliases.hasMoreElements()) {
			tempCertChain = contractCertificateKeystore.getCertificateChain(aliases.nextElement());
			certChain.setCertificate(getLeafCertificate(tempCertChain).getEncoded());
			certChain.setSubCertificates(getSubCertificates(tempCertChain));
		}
	} catch (KeyStoreException | CertificateEncodingException | NullPointerException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while  trying to get " +
						  "certificate chain from resource '" + pkcs12Resource + "'", e);
	}
	
	return certChain;
}
 
Example 7
Project: RISE-V2G   File: SecurityUtils.java   View Source Code Vote up 5 votes
/**
 * Searches a given keystore either for a contract certificate chain or OEM provisioning certificate
 * chain, determined by the alias (the alias is associated with the certificate chain and the private
 * key). 
 * However, it may be the case that more than once contract certificate is installed in the EV, 
 * in which case an OEM specific implementation would need to interact at this point with a HMI in
 * order to enable the user to select the certificate which is to be used for contract based charging.
 * 
 * @param evccKeyStore The keystore to check for the respective certificate chain
 * @param alias The alias associated with a key entry and certificate chain
 * @return The respective certificate chain if present, null otherwise
 */
public static CertificateChainType getCertificateChain(KeyStore evccKeyStore, String alias) {
	CertificateChainType certChain = new CertificateChainType();
	SubCertificatesType subCertificates = new SubCertificatesType();
	
	try {
		Certificate[] certChainArray = evccKeyStore.getCertificateChain(alias);
		
		if (certChainArray == null) {
			getLogger().info("No certificate chain found for alias '" + alias + "'");
			return null;
		}
		
		certChain.setCertificate(certChainArray[0].getEncoded());

		for (int i = 1; i < certChainArray.length; i++) {
			subCertificates.getCertificate().add(certChainArray[i].getEncoded());
		}
		
		certChain.setSubCertificates(subCertificates);
		
		return certChain;
	} catch (KeyStoreException | CertificateEncodingException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while trying to get certificate chain", e);
		return null;
	}
}
 
Example 8
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 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: ipack   File: Signer.java   View Source Code Vote up 4 votes
public static Signer create(
        final File keystoreFile,
        final String keystorePassword,
        final String signingAlias,
        final String keyPassword) throws IOException,
                                         KeyStoreException,
                                         NoSuchAlgorithmException,
                                         CertificateException,
                                         UnrecoverableKeyException,
                                         OperatorCreationException,
                                         CMSException,
                                         InvalidNameException {
    final KeyStore jksKeyStore = KeyStore.getInstance("JKS");
    final InputStream is = new FileInputStream(keystoreFile);
    try {
        jksKeyStore.load(is, keystorePassword.toCharArray());
    } finally {
        is.close();
    }

    final PrivateKey privateKey =
            (PrivateKey) jksKeyStore.getKey(signingAlias,
                                            keyPassword.toCharArray());
    final Certificate[] certChain =
            jksKeyStore.getCertificateChain(signingAlias);
    if (certChain == null) {
        throw new CertificateException(
                "Certificate chain not found under \"" + signingAlias
                                                       + "\"");
    }

    final X509Certificate signingCert = (X509Certificate) certChain[0];
    final String subjectName = getSubjectName(signingCert);

    Certificate[] certChain2;
    if (certChain.length == 3) { //re-order to match the same order in codesign
        certChain2 = new Certificate[3];
        certChain2[0] = certChain[1];
        certChain2[1] = certChain[2];
        certChain2[2] = certChain[0];
    } else {
        certChain2 = certChain;
    }
    final Store certs = new JcaCertStore(Arrays.asList(certChain2));
    final CMSSignedDataGenerator signatureGenerator =
            new CMSSignedDataGenerator();

    signatureGenerator.addSignerInfoGenerator(
            new JcaSimpleSignerInfoGeneratorBuilder()
                        .setProvider("BC")
                        .build("SHA1withRSA", privateKey, signingCert));
    signatureGenerator.addCertificates(certs);

    return new Signer(signatureGenerator, subjectName);
}
 
Example 11
Project: openjdk-jdk10   File: TokenStore.java   View Source Code Vote up 4 votes
private static void init() throws Exception {

        // first write policy files

        PolicyParser pp = new PolicyParser();
        pp.read(new StringReader(POLICY_NO_STORE));
        pp.write(new FileWriter(NO_STORE_FILE, false));

        pp = new PolicyParser();
        pp.read(new StringReader(POLICY_URL));
        pp.write(new FileWriter(URL_FILE, false));

        pp = new PolicyParser();
        pp.read(new StringReader(POLICY_URL_T));
        pp.write(new FileWriter(URL_T_FILE, false));

        pp = new PolicyParser();
        pp.read(new StringReader(POLICY_URL_T_P));
        pp.write(new FileWriter(URL_T_P_FILE, false));

        pp = new PolicyParser();
        pp.read(new StringReader(POLICY_URL_PWD));
        pp.write(new FileWriter(URL_PWD_FILE, false));

        pp = new PolicyParser();
        pp.read(new StringReader(POLICY_URL_T_P_PWD));
        pp.write(new FileWriter(URL_T_P_PWD_FILE, false));

        pp = new PolicyParser();
        pp.read(new StringReader(POLICY_BADPASS));
        pp.write(new FileWriter(BADPASS_FILE, false));

        // next load keystore data to build PD's

        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(new FileInputStream
                        (System.getProperty("test.src", ".") +
                        File.separatorChar +
                        "TokenStore.keystore"),
                storePassword);

        NO_STORE_DOMAIN = new ProtectionDomain
                        (new CodeSource(new URL("file:/foo"),
                            (java.security.cert.Certificate[]) null),
                        null,  // perms
                        null,  // class loader
                        null);  // principals

        Certificate[] chain = (Certificate[])
                        ks.getCertificateChain("POLICY_URL");
        URL_DOMAIN = new ProtectionDomain
                        (new CodeSource(new URL("file:/foo"), chain),
                        null,  // perms
                        null,  // class loader
                        null);  // principals

        chain = (Certificate[])
                        ks.getCertificateChain("POLICY_URL_T");
        URL_T_DOMAIN = new ProtectionDomain
                        (new CodeSource(new URL("file:/foo"), chain),
                        null,  // perms
                        null,  // class loader
                        null);  // principals

        chain = (Certificate[])
                        ks.getCertificateChain("POLICY_URL_T_P");
        URL_T_P_DOMAIN = new ProtectionDomain
                        (new CodeSource(new URL("file:/foo"), chain),
                        null,  // perms
                        null,  // class loader
                        null);  // principals
    }
 
Example 12
Project: openjdk-jdk10   File: PKCS12SameKeyId.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {

        // Prepare a JKS keystore with many entries
        new File(JKSFILE).delete();
        for (int i=0; i<SIZE; i++) {
            System.err.print(".");
            String cmd = "-keystore " + JKSFILE
                    + " -storepass changeit -keypass changeit -keyalg rsa "
                    + "-genkeypair -alias p" + i + " -dname CN=" + i;
            sun.security.tools.keytool.Main.main(cmd.split(" "));
        }

        // Prepare EncryptedPrivateKeyInfo parameters, copied from various
        // places in PKCS12KeyStore.java
        AlgorithmParameters algParams =
                AlgorithmParameters.getInstance("PBEWithSHA1AndDESede");
        algParams.init(new PBEParameterSpec("12345678".getBytes(), 1024));
        AlgorithmId algid = new AlgorithmId(
                new ObjectIdentifier("1.2.840.113549.1.12.1.3"), algParams);

        PBEKeySpec keySpec = new PBEKeySpec(PASSWORD);
        SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
        SecretKey skey = skFac.generateSecret(keySpec);

        Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
        cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);

        // Pre-calculated keys and certs and aliases
        byte[][] keys = new byte[SIZE][];
        Certificate[][] certChains = new Certificate[SIZE][];
        String[] aliases = new String[SIZE];

        // Reads from JKS keystore and pre-calculate
        KeyStore ks = KeyStore.getInstance("jks");
        try (FileInputStream fis = new FileInputStream(JKSFILE)) {
            ks.load(fis, PASSWORD);
        }
        for (int i=0; i<SIZE; i++) {
            aliases[i] = "p" + i;
            byte[] enckey = cipher.doFinal(
                    ks.getKey(aliases[i], PASSWORD).getEncoded());
            keys[i] = new EncryptedPrivateKeyInfo(algid, enckey).getEncoded();
            certChains[i] = ks.getCertificateChain(aliases[i]);
        }

        // Write into PKCS12 keystore. Use this overloaded version of
        // setKeyEntry() to be as fast as possible, so that they would
        // have same localKeyId.
        KeyStore p12 = KeyStore.getInstance("pkcs12");
        p12.load(null, PASSWORD);
        for (int i=0; i<SIZE; i++) {
            p12.setKeyEntry(aliases[i], keys[i], certChains[i]);
        }
        try (FileOutputStream fos = new FileOutputStream(P12FILE)) {
            p12.store(fos, PASSWORD);
        }

        // Check private keys still match certs
        p12 = KeyStore.getInstance("pkcs12");
        try (FileInputStream fis = new FileInputStream(P12FILE)) {
            p12.load(fis, PASSWORD);
        }
        for (int i=0; i<SIZE; i++) {
            String a = "p" + i;
            X509Certificate x = (X509Certificate)p12.getCertificate(a);
            X500Name name = (X500Name)x.getSubjectDN();
            if (!name.getCommonName().equals(""+i)) {
                throw new Exception(a + "'s cert is " + name);
            }
        }
    }
 
Example 13
Project: jdk8u-jdk   File: WriteP12Test.java   View Source Code Vote up 4 votes
private void test(Certificate certs[], String inKeyStorePath,
        String userAlias, String outStorePass, String outKeyPass)
        throws KeyStoreException, NoSuchProviderException, IOException,
        CertificateException, UnrecoverableKeyException,
        NoSuchAlgorithmException {
    // init output key store
    KeyStore outputKeyStore = KeyStore.getInstance("pkcs12", "SunJSSE");
    outputKeyStore.load(null, null);
    try (FileOutputStream fout = new FileOutputStream(OUT_KEYSTORE)) {
        // KeyStore have encoded by Base64.getMimeEncoder().encode(),need
        // decode first.
        byte[] input = Files.readAllBytes(Paths.get(CERT_PATH,
                inKeyStorePath));
        ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64
                .getMimeDecoder().decode(input));
        // input key store
        KeyStore inputKeyStore = KeyStore.getInstance(IN_KEYSTORE_TYPE,
                IN_KEYSTORE_PRV);
        inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray());
        // add key/certificate to output key store
        Key key = inputKeyStore
                .getKey(userAlias, IN_KEY_PASS.toCharArray());
        out.println("Input Key Algorithm " + key.getAlgorithm());
        out.println("====Input Certs=====");
        if (certs == null) {
            certs = new Certificate[] { inputKeyStore
                    .getCertificate(userAlias) };
        }
        for (Certificate cert : certs) {
            out.println(((X509Certificate) cert).getSubjectDN());
        }
        outputKeyStore.setKeyEntry(userAlias, key,
                outKeyPass.toCharArray(), certs);
        Certificate retCerts[] = outputKeyStore
                .getCertificateChain(userAlias);
        out.println("====Output Certs=====");
        for (Certificate retCert : retCerts) {
            out.println(((X509Certificate) retCert).getSubjectDN());
        }
        out.println("====Output Key Algorithm=====");
        Key outKey = outputKeyStore.getKey(userAlias,
                outKeyPass.toCharArray());
        out.println(outKey.getAlgorithm());

        if (!key.equals(outKey)) {
            throw new RuntimeException("key don't match");
        }
        if (!Arrays.equals(certs, retCerts)) {
            throw new RuntimeException("certs don't match");
        }
        // save output
        outputKeyStore.store(fout, outStorePass.toCharArray());
        // test output
        testKeyStore(outputKeyStore, outKeyPass.toCharArray());
    }
}
 
Example 14
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 15
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 16
Project: BiglyBT   File: SESecurityManagerImpl.java   View Source Code Vote up 4 votes
public SEKeyDetails
getKeyDetails(
	String		alias )

	throws Exception
{
	// Create the key manager factory used to extract the server key

	KeyStore key_store = loadKeyStore();

	final Key key = key_store.getKey( alias, SESecurityManager.SSL_PASSWORD.toCharArray());

	if ( key == null ){

		return( null );
	}

	java.security.cert.Certificate[]	chain = key_store.getCertificateChain( alias );

	final X509Certificate[]	res = new X509Certificate[chain.length];

	for (int i=0;i<chain.length;i++){

		if ( !( chain[i] instanceof X509Certificate )){

			throw( new Exception( "Certificate chain must be comprised of X509Certificate entries"));
		}

		res[i] = (X509Certificate)chain[i];
	}

	return( new SEKeyDetails()
			{
				@Override
				public Key
				getKey()
				{
					return( key );
				}

				@Override
				public X509Certificate[]
				getCertificateChain()
				{
					return( res );
				}
			});
}
 
Example 17
Project: jdk8u-jdk   File: PKCS12SameKeyId.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {

        // Prepare a JKS keystore with many entries
        new File(JKSFILE).delete();
        for (int i=0; i<SIZE; i++) {
            System.err.print(".");
            String cmd = "-keystore " + JKSFILE
                    + " -storepass changeit -keypass changeit -keyalg rsa "
                    + "-genkeypair -alias p" + i + " -dname CN=" + i;
            sun.security.tools.keytool.Main.main(cmd.split(" "));
        }

        // Prepare EncryptedPrivateKeyInfo parameters, copied from various
        // places in PKCS12KeyStore.java
        AlgorithmParameters algParams =
                AlgorithmParameters.getInstance("PBEWithSHA1AndDESede");
        algParams.init(new PBEParameterSpec("12345678".getBytes(), 1024));
        AlgorithmId algid = new AlgorithmId(
                new ObjectIdentifier("1.2.840.113549.1.12.1.3"), algParams);

        PBEKeySpec keySpec = new PBEKeySpec(PASSWORD);
        SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
        SecretKey skey = skFac.generateSecret(keySpec);

        Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
        cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);

        // Pre-calculated keys and certs and aliases
        byte[][] keys = new byte[SIZE][];
        Certificate[][] certChains = new Certificate[SIZE][];
        String[] aliases = new String[SIZE];

        // Reads from JKS keystore and pre-calculate
        KeyStore ks = KeyStore.getInstance("jks");
        try (FileInputStream fis = new FileInputStream(JKSFILE)) {
            ks.load(fis, PASSWORD);
        }
        for (int i=0; i<SIZE; i++) {
            aliases[i] = "p" + i;
            byte[] enckey = cipher.doFinal(
                    ks.getKey(aliases[i], PASSWORD).getEncoded());
            keys[i] = new EncryptedPrivateKeyInfo(algid, enckey).getEncoded();
            certChains[i] = ks.getCertificateChain(aliases[i]);
        }

        // Write into PKCS12 keystore. Use this overloaded version of
        // setKeyEntry() to be as fast as possible, so that they would
        // have same localKeyId.
        KeyStore p12 = KeyStore.getInstance("pkcs12");
        p12.load(null, PASSWORD);
        for (int i=0; i<SIZE; i++) {
            p12.setKeyEntry(aliases[i], keys[i], certChains[i]);
        }
        try (FileOutputStream fos = new FileOutputStream(P12FILE)) {
            p12.store(fos, PASSWORD);
        }

        // Check private keys still match certs
        p12 = KeyStore.getInstance("pkcs12");
        try (FileInputStream fis = new FileInputStream(P12FILE)) {
            p12.load(fis, PASSWORD);
        }
        for (int i=0; i<SIZE; i++) {
            String a = "p" + i;
            X509Certificate x = (X509Certificate)p12.getCertificate(a);
            X500Name name = (X500Name)x.getSubjectDN();
            if (!name.getCommonName().equals(""+i)) {
                throw new Exception(a + "'s cert is " + name);
            }
        }
    }
 
Example 18
Project: openjdk-jdk10   File: WriteP12Test.java   View Source Code Vote up 4 votes
private void test(Certificate certs[], String inKeyStorePath,
        String userAlias, String outStorePass, String outKeyPass)
        throws KeyStoreException, NoSuchProviderException, IOException,
        CertificateException, UnrecoverableKeyException,
        NoSuchAlgorithmException {
    // init output key store
    KeyStore outputKeyStore = KeyStore.getInstance("pkcs12", "SunJSSE");
    outputKeyStore.load(null, null);
    try (FileOutputStream fout = new FileOutputStream(OUT_KEYSTORE)) {
        // KeyStore have encoded by Base64.getMimeEncoder().encode(),need
        // decode first.
        byte[] input = Files.readAllBytes(Paths.get(CERT_PATH,
                inKeyStorePath));
        ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64
                .getMimeDecoder().decode(input));
        // input key store
        KeyStore inputKeyStore = KeyStore.getInstance(IN_KEYSTORE_TYPE,
                IN_KEYSTORE_PRV);
        inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray());
        // add key/certificate to output key store
        Key key = inputKeyStore
                .getKey(userAlias, IN_KEY_PASS.toCharArray());
        out.println("Input Key Algorithm " + key.getAlgorithm());
        out.println("====Input Certs=====");
        if (certs == null) {
            certs = new Certificate[] { inputKeyStore
                    .getCertificate(userAlias) };
        }
        for (Certificate cert : certs) {
            out.println(((X509Certificate) cert).getSubjectDN());
        }
        outputKeyStore.setKeyEntry(userAlias, key,
                outKeyPass.toCharArray(), certs);
        Certificate retCerts[] = outputKeyStore
                .getCertificateChain(userAlias);
        out.println("====Output Certs=====");
        for (Certificate retCert : retCerts) {
            out.println(((X509Certificate) retCert).getSubjectDN());
        }
        out.println("====Output Key Algorithm=====");
        Key outKey = outputKeyStore.getKey(userAlias,
                outKeyPass.toCharArray());
        out.println(outKey.getAlgorithm());

        if (!key.equals(outKey)) {
            throw new RuntimeException("key don't match");
        }
        if (!Arrays.equals(certs, retCerts)) {
            throw new RuntimeException("certs don't match");
        }
        // save output
        outputKeyStore.store(fout, outStorePass.toCharArray());
        // test output
        testKeyStore(outputKeyStore, outKeyPass.toCharArray());
    }
}
 
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");
        }

    }