Java Code Examples for java.security.KeyStore#getCertificateChain()
The following examples show how to use
java.security.KeyStore#getCertificateChain() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KeyStoreTest.java From athenz with Apache License 2.0 | 6 votes |
@Test public void testCreateKeyStoreFromPems() throws Exception { String athenzPublicCertPem = Resources.toString( Resources.getResource("rsa_public_x510_w_intermediate.cert"), StandardCharsets.UTF_8); String athenzPrivateKeyPem = Resources.toString( Resources.getResource("unit_test_rsa_private.key"), StandardCharsets.UTF_8); KeyStore keyStore = Utils.createKeyStoreFromPems(athenzPublicCertPem, athenzPrivateKeyPem); assertNotNull(keyStore); String alias = null; for (Enumeration<?> e = keyStore.aliases(); e.hasMoreElements(); ) { alias = (String) e.nextElement(); assertEquals(ALIAS_NAME, alias); } X509Certificate[] chain = (X509Certificate[]) keyStore.getCertificateChain(alias); assertNotNull(chain); assertTrue(chain.length == 2); }
Example 2
Source File: PEMImporterTest.java From zeppelin with Apache License 2.0 | 6 votes |
@Test public void testCertKeyAndChain() throws Exception { KeyStore truststore = PEMImporter.loadTrustStore(rootCACert); KeyStore keystore = PEMImporter.loadKeyStore(pemCert, pemkey, ""); assertEquals(1, keystore.size()); assertTrue(keystore.containsAlias("key")); assertEquals(1, keystore.getCertificateChain("key").length); assertEquals(1, truststore.size()); Certificate[] certs = keystore.getCertificateChain("key"); PublicKey publicKey = certs[0].getPublicKey(); PrivateKey privateKey = (PrivateKey) keystore.getKey("key", "".toCharArray()); assertTrue(verifyPubAndPrivKey(publicKey, privateKey)); X509Certificate ca = (X509Certificate) truststore.getCertificate("cn=localhost"); X509Certificate cert = (X509Certificate) keystore.getCertificate("key"); assertTrue(verifyChain(cert, ca)); }
Example 3
Source File: CryptoImpl.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
private SigningCredential retrieveSigningCredential(String alias, KeyStore keyStore) { try { Certificate[] c = keyStore.getCertificateChain(alias); if (ArrayUtils.isEmpty(c)) { throw new IllegalArgumentException("The KeyStore doesn't contain the required key with alias [" + alias + "]"); } else { X509Certificate[] certificateChain = (X509Certificate[])Arrays.copyOf(c, c.length, X509Certificate[].class); PrivateKey privateKey = (PrivateKey)keyStore.getKey(alias, (char[])null); return SigningCredential.create(privateKey, Iterables.newList(certificateChain)); } } catch (KeyStoreException var6) { throw new IllegalArgumentException("Given keystore hasn't been initialized", var6); } catch (NoSuchAlgorithmException var7) { throw new IllegalStateException("There is a problem with the Security configuration... Check if all the required security providers are correctly registered", var7); } catch (UnrecoverableKeyException var8) { throw new IllegalStateException("The private key with alias [" + alias + "] could not be recovered from the given keystore", var8); } }
Example 4
Source File: ConvertP12Test.java From openjdk-jdk8u with GNU General Public License v2.0 | 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 5
Source File: SunX509KeyManagerImpl.java From Bytecoder with Apache License 2.0 | 5 votes |
SunX509KeyManagerImpl(KeyStore ks, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { credentialsMap = new HashMap<String,X509Credentials>(); serverAliasCache = Collections.synchronizedMap( new HashMap<String,String[]>()); if (ks == null) { return; } for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements(); ) { String alias = aliases.nextElement(); if (!ks.isKeyEntry(alias)) { continue; } Key key = ks.getKey(alias, password); if (key instanceof PrivateKey == false) { continue; } Certificate[] certs = ks.getCertificateChain(alias); if ((certs == null) || (certs.length == 0) || !(certs[0] instanceof X509Certificate)) { continue; } if (!(certs instanceof X509Certificate[])) { Certificate[] tmp = new X509Certificate[certs.length]; System.arraycopy(certs, 0, tmp, 0, certs.length); certs = tmp; } X509Credentials cred = new X509Credentials((PrivateKey)key, (X509Certificate[])certs); credentialsMap.put(alias, cred); if (SSLLogger.isOn && SSLLogger.isOn("keymanager")) { SSLLogger.fine("found key for : " + alias, (Object[])certs); } } }
Example 6
Source File: Utilities.java From netbeans with Apache License 2.0 | 5 votes |
public static Collection<Certificate> getCertificates (KeyStore keyStore) throws KeyStoreException { Set<Certificate> certs = new HashSet<> (); 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 7
Source File: FtpsClient.java From ats-framework with Apache License 2.0 | 5 votes |
public DefaultTrustStrategy( KeyStore trustStore ) throws Exception { /** get all certificates from the trust store **/ Enumeration<String> aliases = trustStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (trustStore.isCertificateEntry(alias)) { /** the alias points to a certificate **/ certificates.add(trustStore.getCertificate(alias)); } else { /** the alias does not point to a certificate, * but this may mean that it points to a private-public key pair or a certificate chain */ Certificate certificate = trustStore.getCertificate(alias); if (certificate != null) { /** * the certificate was extracted from a private-public key entry * */ certificates.add(certificate); } else { /** * the alias points to a certificate chain * */ Certificate[] chain = trustStore.getCertificateChain(alias); for (Certificate cert : chain) { certificates.add(cert); } } } } }
Example 8
Source File: ApkSignerUtil.java From mollyim-android with GNU General Public License v3.0 | 5 votes |
private ApkSigner.SignerConfig loadKeyStore(String keyStoreType, String keyStorePassword) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException { KeyStore keyStoreEntity = KeyStore.getInstance(keyStoreType == null ? KeyStore.getDefaultType() : keyStoreType); char[] password = getPassword(keyStorePassword); keyStoreEntity.load(null, password); Enumeration<String> aliases = keyStoreEntity.aliases(); String keyAlias = null; while (aliases != null && aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keyStoreEntity.isKeyEntry(alias)) { keyAlias = alias; break; } } if (keyAlias == null) { throw new IllegalArgumentException("Keystore has no key entries!"); } PrivateKey privateKey = (PrivateKey) keyStoreEntity.getKey(keyAlias, password); Certificate[] certificates = keyStoreEntity.getCertificateChain(keyAlias); if (certificates == null || certificates.length == 0) { throw new IllegalArgumentException("Unable to load certificates!"); } List<X509Certificate> results = new LinkedList<>(); for (Certificate certificate : certificates) { results.add((X509Certificate)certificate); } return new ApkSigner.SignerConfig.Builder("Signal Signer", privateKey, results).build(); }
Example 9
Source File: SecurityUtils.java From RISE-V2G with MIT License | 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 10
Source File: WriteP12Test.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 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 11
Source File: SMIMEKeyHolder.java From james-project with Apache License 2.0 | 4 votes |
/** * Creates a new instance of <CODE>KeyHolder</CODE> using {@link java.security.KeyStore} related parameters. * @param keyStoreFileName The (absolute) file name of the .keystore file to load the keystore from. * @param keyStorePassword The (optional) password used to check the integrity of the keystore. * If given, it is used to check the integrity of the keystore data, * otherwise, if null, the integrity of the keystore is not checked. * @param keyAlias The alias name of the key. * If missing (is null) and if there is only one key in the keystore, will default to it. * @param keyAliasPassword The password of the alias for recovering the key. * If missing (is null) will default to <I>keyStorePassword</I>. At least one of the passwords must be provided. * @param keyStoreType The type of keystore. * If missing (is null) will default to the keystore type as specified in the Java security properties file, * or the string "jks" (acronym for "Java keystore") if no such property exists. * @throws java.security.KeyStoreException Thrown when the <I>keyAlias</I> is specified and not found, * or is not specified and either no alias is found or more than one is found. * @see java.security.KeyStore#getDefaultType * @see java.security.KeyStore#getInstance(String) * @see java.security.KeyStore#load * @see java.security.KeyStore#getKey * @see java.security.KeyStore#getCertificate */ public SMIMEKeyHolder(String keyStoreFileName, String keyStorePassword, String keyAlias, String keyAliasPassword, String keyStoreType) throws KeyStoreException, IOException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, CertificateException, UnrecoverableKeyException, NoSuchProviderException { try { InitJCE.init(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { NoSuchProviderException ex = new NoSuchProviderException("Error during cryptography provider initialization. Has bcprov-jdkxx-yyy.jar been copied in the lib directory or installed in the system?"); ex.initCause(e); throw ex; } if (keyStoreType == null) { keyStoreType = KeyStore.getDefaultType(); } KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(new BufferedInputStream(new FileInputStream(keyStoreFileName)), keyStorePassword.toCharArray()); Enumeration<String> aliases = keyStore.aliases(); if (keyAlias == null) { if (aliases.hasMoreElements()) { keyAlias = aliases.nextElement(); } else { throw new KeyStoreException("No alias was found in keystore."); } if (aliases.hasMoreElements()) { throw new KeyStoreException("No <keyAlias> was given and more than one alias was found in keystore."); } } if (keyAliasPassword == null) { keyAliasPassword = keyStorePassword; } this.privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyAliasPassword.toCharArray()); if (this.privateKey == null) { throw new KeyStoreException("The \"" + keyAlias + "\" PrivateKey alias was not found in keystore."); } this.certificate = (X509Certificate) keyStore.getCertificate(keyAlias); if (this.certificate == null) { throw new KeyStoreException("The \"" + keyAlias + "\" X509Certificate alias was not found in keystore."); } java.security.cert.Certificate[] certificateChain = keyStore.getCertificateChain(keyAlias); ArrayList<java.security.cert.Certificate> certList = new ArrayList<>(); if (certificateChain == null) { certList.add(this.certificate); } else { Collections.addAll(certList, certificateChain); } // create a CertStore containing the certificates we want carried // in the signature this.certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); jcaCertStore = new JcaCertStore(certList); }
Example 12
Source File: PKCS12SameKeyId.java From TencentKona-8 with GNU General Public License v2.0 | 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
Source File: ReadP12Test.java From openjdk-jdk8u with GNU General Public License v2.0 | 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 14
Source File: TokenStore.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 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 15
Source File: FileTransferHttpClient.java From ats-framework with Apache License 2.0 | 4 votes |
@Override public void setTrustStore( String truststoreFile, String truststorePassword ) { try { KeyStore trustStore = SslUtils.loadKeystore(truststoreFile, truststorePassword); List<Certificate> certificates = new ArrayList<Certificate>(); /** get all certificates from the trust store **/ Enumeration<String> aliases = trustStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (trustStore.isCertificateEntry(alias)) { /** the alias points to a certificate **/ certificates.add(trustStore.getCertificate(alias)); } else { /** the alias does not point to a certificate, * but this may mean that it points to a private-public key pair or certificate chain */ Certificate certificate = trustStore.getCertificate(alias); if (certificate != null) { /** * the certificate was extracted from a private-public key entry * */ certificates.add(certificate); } else { /** * the alias points to a certificate chain * */ Certificate[] chain = trustStore.getCertificateChain(alias); for (Certificate cert : chain) { certificates.add(cert); } } } } trustedServerCertificates = new X509Certificate[certificates.size()]; certificates.toArray(trustedServerCertificates); } catch (Exception e) { throw new HttpException("Unable to load all certificates from the trust store", e); } }
Example 16
Source File: AddPrivateKey.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
private static void test(Provider p, PrivateKeyEntry entry) throws Exception { PrivateKey key = entry.getPrivateKey(); X509Certificate[] chain = (X509Certificate[])entry.getCertificateChain(); PublicKey publicKey = chain[0].getPublicKey(); System.out.println(toString(key)); sign(p, key, publicKey); KeyStore ks = KeyStore.getInstance("PKCS11", p); ks.load(null, null); if (ks.size() != 0) { throw new Exception("KeyStore not empty"); } List<String> aliases; // test 1: add entry ks.setKeyEntry(ALIAS1, key, null, chain); aliases = aliases(ks); if (aliases.size() != 1) { throw new Exception("size not 1: " + aliases); } if (aliases.get(0).equals(ALIAS1) == false) { throw new Exception("alias mismatch: " + aliases); } PrivateKey key2 = (PrivateKey)ks.getKey(ALIAS1, null); System.out.println(toString(key2)); X509Certificate[] chain2 = (X509Certificate[]) ks.getCertificateChain(ALIAS1); if (Arrays.equals(chain, chain2) == false) { throw new Exception("chain mismatch"); } sign(p, key2, publicKey); ks.deleteEntry(ALIAS1); if (ks.size() != 0) { throw new Exception("KeyStore not empty"); } // test 2: translate to session object, then add entry KeyFactory kf = KeyFactory.getInstance(key.getAlgorithm(), p); PrivateKey key3 = (PrivateKey)kf.translateKey(key); System.out.println(toString(key3)); sign(p, key3, publicKey); ks.setKeyEntry(ALIAS2, key3, null, chain); aliases = aliases(ks); if (aliases.size() != 1) { throw new Exception("size not 1"); } if (aliases.get(0).equals(ALIAS2) == false) { throw new Exception("alias mismatch: " + aliases); } PrivateKey key4 = (PrivateKey)ks.getKey(ALIAS2, null); System.out.println(toString(key4)); X509Certificate[] chain4 = (X509Certificate[]) ks.getCertificateChain(ALIAS2); if (Arrays.equals(chain, chain4) == false) { throw new Exception("chain mismatch"); } sign(p, key4, publicKey); // test 3: change alias ks.setKeyEntry(ALIAS3, key3, null, chain); aliases = aliases(ks); if (aliases.size() != 1) { throw new Exception("size not 1"); } if (aliases.get(0).equals(ALIAS3) == false) { throw new Exception("alias mismatch: " + aliases); } PrivateKey key5 = (PrivateKey)ks.getKey(ALIAS3, null); System.out.println(toString(key5)); X509Certificate[] chain5 = (X509Certificate[]) ks.getCertificateChain(ALIAS3); if (Arrays.equals(chain, chain5) == false) { throw new Exception("chain mismatch"); } sign(p, key5, publicKey); ks.deleteEntry(ALIAS3); if (ks.size() != 0) { throw new Exception("KeyStore not empty"); } System.out.println("OK"); }
Example 17
Source File: WriteP12Test.java From openjdk-jdk8u with GNU General Public License v2.0 | 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
Source File: WriteP12Test.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 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
Source File: WriteP12Test.java From jdk8u_jdk with GNU General Public License v2.0 | 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 20
Source File: CryptoUtil.java From micro-integrator with Apache License 2.0 | 4 votes |
/** * Encrypt a given plain text * * @param plainTextBytes The plaintext bytes to be encrypted * @param cipherTransformation The transformation that need to encrypt. If it is null, RSA is used as default * @param returnSelfContainedCipherText Create self-contained cipher text if true, return simple encrypted * ciphertext otherwise. * @return The cipher text bytes * @throws org.wso2.micro.core.util.CryptoException On error during encryption */ public byte[] encrypt(byte[] plainTextBytes, String cipherTransformation, boolean returnSelfContainedCipherText) throws org.wso2.micro.core.util.CryptoException { byte[] encryptedKey; org.wso2.micro.core.encryption.SymmetricEncryption encryption = org.wso2.micro.core.encryption.SymmetricEncryption .getInstance(); try { if (Boolean.valueOf(encryption.getSymmetricKeyEncryptEnabled())) { encryptedKey = encryption.encryptWithSymmetricKey(plainTextBytes); } else { Cipher keyStoreCipher; KeyStore keyStore; Certificate[] certs; org.wso2.micro.core.util.KeyStoreManager keyMan = org.wso2.micro.core.util.KeyStoreManager.getInstance( Constants.SUPER_TENANT_ID, this.getServerConfigService()); if (keyMan.getInternalKeyStore() != null) { keyStore = keyMan.getInternalKeyStore(); certs = keyStore.getCertificateChain(internalKeyStoreAlias); } else { keyStore = keyMan.getPrimaryKeyStore(); certs = keyStore.getCertificateChain(primaryKeyStoreAlias); } boolean isCipherTransformEnabled = false; if (cipherTransformation != null) { if (log.isDebugEnabled()) { log.debug("Cipher transformation for encryption : " + cipherTransformation); } keyStoreCipher = Cipher.getInstance(cipherTransformation, "BC"); isCipherTransformEnabled = true; } else { if (log.isDebugEnabled()) { log.debug("Default Cipher transformation for encryption : RSA"); } keyStoreCipher = Cipher.getInstance("RSA", "BC"); } keyStoreCipher.init(Cipher.ENCRYPT_MODE, certs[0].getPublicKey()); if (isCipherTransformEnabled && plainTextBytes.length == 0) { encryptedKey = "".getBytes(); if (log.isDebugEnabled()) { log.debug("Empty value for plainTextBytes null will persist to DB"); } } else { encryptedKey = keyStoreCipher.doFinal(plainTextBytes); } if (isCipherTransformEnabled && returnSelfContainedCipherText) { encryptedKey = createSelfContainedCiphertext(encryptedKey, cipherTransformation, certs[0]); } } } catch (Exception e) { throw new org.wso2.micro.core.util.CryptoException("Error during encryption", e); } return encryptedKey; }