List of usage examples for java.security KeyStore getCertificateChain
public final Certificate[] getCertificateChain(String alias) throws KeyStoreException
From source file:org.apache.ws.security.components.crypto.Merlin.java
/** * Get an implementation-specific identifier that corresponds to the X509Certificate. In * this case, the identifier is the KeyStore alias. * @param cert The X509Certificate corresponding to the returned identifier * @param store The KeyStore to search// w ww .j av a 2s .co m * @return An implementation-specific identifier that corresponds to the X509Certificate */ private String getIdentifier(X509Certificate cert, KeyStore store) throws WSSecurityException { try { for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) { String alias = e.nextElement(); Certificate[] certs = store.getCertificateChain(alias); Certificate retrievedCert = null; if (certs == null || certs.length == 0) { // no cert chain, so lets check if getCertificate gives us a result. retrievedCert = store.getCertificate(alias); if (retrievedCert == null) { continue; } } else { retrievedCert = certs[0]; } if (!(retrievedCert instanceof X509Certificate)) { continue; } if (retrievedCert.equals(cert)) { return alias; } } } catch (KeyStoreException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e); } return null; }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplTest.java
/** * Test method for {@link net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl#exportKeyPair(java.lang.String, java.io.File, java.lang.String)}. * @throws CMException //from ww w . ja v a2 s . c o m * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws UnrecoverableKeyException */ @Test public void testExportKeyPair() throws CMException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException { String alias = credentialManager.addKeyPair(privateKey, privateKeyCertChain); File fileToExportTo = new File(credentialManagerDirectory, "test-export-key.p12"); credentialManager.exportKeyPair(alias, fileToExportTo, privateKeyAndPKCS12KeystorePassword); assertTrue(fileToExportTo.exists()); // Load it back from the file we just saved KeyStore ks = credentialManager.loadPKCS12Keystore(fileToExportTo, privateKeyAndPKCS12KeystorePassword); Enumeration<String> aliases = ks.aliases(); Key newPrivateKey = null; Certificate[] newPrivateKeyCerts = null; while (aliases.hasMoreElements()) { // The test-private-key-cert.p12 file contains only one private key // and corresponding certificate entry alias = aliases.nextElement(); if (ks.isKeyEntry(alias)) { // is it a (private) key entry? newPrivateKey = ks.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray()); newPrivateKeyCerts = ks.getCertificateChain(alias); break; } } assertNotNull(newPrivateKey); assertNotNull(newPrivateKeyCerts); //assertTrue(Arrays.equals(newPrivateKey.getEncoded(), privateKey.getEncoded())); assertTrue(newPrivateKey.equals(privateKey)); assertTrue(Arrays.equals(newPrivateKeyCerts, privateKeyCertChain)); }
From source file:org.apache.ws.security.components.crypto.Merlin.java
/** * Get an X509 Certificate (chain) of the X500Principal argument in the supplied KeyStore * @param subjectRDN either an X500Principal or a BouncyCastle X509Name instance. * @param store The KeyStore//from w w w .j a v a 2 s . c om * @return an X509 Certificate (chain) * @throws WSSecurityException */ private Certificate[] getCertificates(byte[] skiBytes, KeyStore store) throws WSSecurityException { try { for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) { String alias = e.nextElement(); Certificate cert = null; Certificate[] certs = store.getCertificateChain(alias); if (certs == null || certs.length == 0) { // no cert chain, so lets check if getCertificate gives us a result. cert = store.getCertificate(alias); if (cert == null) { continue; } certs = new Certificate[] { cert }; } else { cert = certs[0]; } if (cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; byte[] data = getSKIBytesFromCert(x509cert); if (data.length == skiBytes.length && Arrays.equals(data, skiBytes)) { return certs; } } } } catch (KeyStoreException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e); } return new Certificate[] {}; }
From source file:org.apache.ws.security.components.crypto.Merlin.java
/** * Get an X509 Certificate (chain) of the X500Principal argument in the supplied KeyStore * @param subjectRDN either an X500Principal or a BouncyCastle X509Name instance. * @param store The KeyStore//from w w w . j ava 2 s .c om * @return an X509 Certificate (chain) * @throws WSSecurityException */ private Certificate[] getCertificates(Object subjectRDN, KeyStore store) throws WSSecurityException { try { for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) { String alias = e.nextElement(); Certificate cert = null; Certificate[] certs = store.getCertificateChain(alias); if (certs == null || certs.length == 0) { // no cert chain, so lets check if getCertificate gives us a result. cert = store.getCertificate(alias); if (cert == null) { continue; } certs = new Certificate[] { cert }; } else { cert = certs[0]; } if (cert instanceof X509Certificate) { X500Principal foundRDN = ((X509Certificate) cert).getSubjectX500Principal(); Object certName = createBCX509Name(foundRDN.getName()); if (subjectRDN.equals(certName)) { return certs; } } } } catch (KeyStoreException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e); } return new Certificate[] {}; }
From source file:org.apache.ws.security.components.crypto.Merlin.java
/** * Get an X509 Certificate (chain) of the X500Principal argument in the supplied KeyStore * @param subjectRDN either an X500Principal or a BouncyCastle X509Name instance. * @param store The KeyStore// w w w .j a va 2 s. c o m * @return an X509 Certificate (chain) * @throws WSSecurityException */ private Certificate[] getCertificates(Object issuerRDN, BigInteger serialNumber, KeyStore store) throws WSSecurityException { try { for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) { String alias = e.nextElement(); Certificate cert = null; Certificate[] certs = store.getCertificateChain(alias); if (certs == null || certs.length == 0) { // no cert chain, so lets check if getCertificate gives us a result. cert = store.getCertificate(alias); if (cert == null) { continue; } certs = new Certificate[] { cert }; } else { cert = certs[0]; } if (cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; if (x509cert.getSerialNumber().compareTo(serialNumber) == 0) { Object certName = createBCX509Name(x509cert.getIssuerX500Principal().getName()); if (certName.equals(issuerRDN)) { return certs; } } } } } catch (KeyStoreException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e); } return new Certificate[] {}; }
From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImplTest.java
/** * Test method for {@link org.apache.taverna.security.credentialmanager.impl.CredentialManagerImpl#exportKeyPair(java.lang.String, java.io.File, java.lang.String)}. * @throws CMException //from w w w . j a v a 2s .co m * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws UnrecoverableKeyException */ @Test public void testExportKeyPair() throws CMException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException { String alias = credentialManager.addKeyPair(privateKey, privateKeyCertChain); File fileToExportTo = new File(credentialManagerDirectory, "test-export-key.p12"); credentialManager.exportKeyPair(alias, fileToExportTo.toPath(), privateKeyAndPKCS12KeystorePassword); assertTrue(fileToExportTo.exists()); // Load it back from the file we just saved KeyStore ks = credentialManager.loadPKCS12Keystore(fileToExportTo.toPath(), privateKeyAndPKCS12KeystorePassword); Enumeration<String> aliases = ks.aliases(); Key newPrivateKey = null; Certificate[] newPrivateKeyCerts = null; while (aliases.hasMoreElements()) { // The test-private-key-cert.p12 file contains only one private key // and corresponding certificate entry alias = aliases.nextElement(); if (ks.isKeyEntry(alias)) { // is it a (private) key entry? newPrivateKey = ks.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray()); newPrivateKeyCerts = ks.getCertificateChain(alias); break; } } assertNotNull(newPrivateKey); assertNotNull(newPrivateKeyCerts); //assertTrue(Arrays.equals(newPrivateKey.getEncoded(), privateKey.getEncoded())); assertTrue(newPrivateKey.equals(privateKey)); assertTrue(Arrays.equals(newPrivateKeyCerts, privateKeyCertChain)); }
From source file:org.apache.ws.security.components.crypto.Merlin.java
/** * Find the Public Key in a keystore. /*from w ww .j av a 2 s . co m*/ */ private boolean findPublicKeyInKeyStore(PublicKey publicKey, KeyStore keyStoreToSearch) { if (keyStoreToSearch == null) { return false; } try { for (Enumeration<String> e = keyStoreToSearch.aliases(); e.hasMoreElements();) { String alias = e.nextElement(); Certificate[] certs = keyStoreToSearch.getCertificateChain(alias); Certificate cert; if (certs == null || certs.length == 0) { // no cert chain, so lets check if getCertificate gives us a result. cert = keyStoreToSearch.getCertificate(alias); if (cert == null) { continue; } } else { cert = certs[0]; } if (!(cert instanceof X509Certificate)) { continue; } X509Certificate x509cert = (X509Certificate) cert; if (publicKey.equals(x509cert.getPublicKey())) { return true; } } } catch (KeyStoreException e) { return false; } return false; }
From source file:org.apache.ws.security.components.crypto.Merlin.java
/** * Get an X509 Certificate (chain) of the X500Principal argument in the supplied KeyStore * @param subjectRDN either an X500Principal or a BouncyCastle X509Name instance. * @param store The KeyStore/*w w w. ja v a 2 s .co m*/ * @return an X509 Certificate (chain) * @throws WSSecurityException */ private Certificate[] getCertificates(byte[] thumbprint, KeyStore store, MessageDigest sha) throws WSSecurityException { try { for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) { String alias = e.nextElement(); Certificate cert = null; Certificate[] certs = store.getCertificateChain(alias); if (certs == null || certs.length == 0) { // no cert chain, so lets check if getCertificate gives us a result. cert = store.getCertificate(alias); if (cert == null) { continue; } certs = new Certificate[] { cert }; } else { cert = certs[0]; } if (cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; try { sha.update(x509cert.getEncoded()); } catch (CertificateEncodingException ex) { throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError", null, ex); } byte[] data = sha.digest(); if (Arrays.equals(data, thumbprint)) { return certs; } } } } catch (KeyStoreException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e); } return new Certificate[] {}; }
From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java
private void logKeyStore(KeyStore ks, String ksLocation, char[] ksPwd) { if (log.isInfoEnabled()) { log.info("Loaded cluster key store from: {}", ksLocation); try {//w w w . j a v a 2 s .c om for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) { String alias = e.nextElement(); Key key = ks.getKey(alias, ksPwd); Certificate[] certs = ks.getCertificateChain(alias); log.debug("{} -> {}", alias, certs); final byte[] encodedKey; if (certs != null && certs.length > 0) { encodedKey = certs[0].getEncoded(); } else { log.info("Could not find cert chain for {}, using fingerprint of key instead...", alias); encodedKey = key.getEncoded(); } // Compute the certificate's fingerprint (use the key if certificate cannot be found) MessageDigest digest = MessageDigest.getInstance("SHA1"); digest.update(encodedKey); StringJoiner fingerprint = new StringJoiner(":"); for (byte b : digest.digest()) { fingerprint.add(String.format("%02X", b)); } log.info("{} -> {}", alias, fingerprint); } } catch (Exception e) { log.warn("Unable to print contents of key store: {}", ksLocation, e); } } }
From source file:net.jsign.PESignerCLI.java
void execute(String... args) throws SignerException { DefaultParser parser = new DefaultParser(); try {/*w w w . ja v a 2s . co m*/ CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help") || args.length == 0) { printHelp(); return; } File keystore = cmd.hasOption("keystore") ? new File(cmd.getOptionValue("keystore")) : null; String storepass = cmd.getOptionValue("storepass"); String storetype = cmd.getOptionValue("storetype"); String alias = cmd.getOptionValue("alias"); String keypass = cmd.getOptionValue("keypass"); File keyfile = cmd.hasOption("keyfile") ? new File(cmd.getOptionValue("keyfile")) : null; File certfile = cmd.hasOption("certfile") ? new File(cmd.getOptionValue("certfile")) : null; String tsaurl = cmd.getOptionValue("tsaurl"); String tsmode = cmd.getOptionValue("tsmode"); String algorithm = cmd.getOptionValue("alg"); String name = cmd.getOptionValue("name"); String url = cmd.getOptionValue("url"); File file = cmd.getArgList().isEmpty() ? null : new File(cmd.getArgList().get(0)); if (keystore != null && storetype == null) { // guess the type of the keystore from the extension of the file String filename = keystore.getName().toLowerCase(); if (filename.endsWith(".p12") || filename.endsWith(".pfx")) { storetype = "PKCS12"; } else { storetype = "JKS"; } } PrivateKey privateKey; Certificate[] chain; // some exciting parameter validation... if (keystore == null && keyfile == null && certfile == null) { throw new SignerException("keystore option, or keyfile and certfile options must be set"); } if (keystore != null && (keyfile != null || certfile != null)) { throw new SignerException("keystore option can't be mixed with keyfile or certfile"); } if (keystore != null) { // JKS or PKCS12 keystore KeyStore ks; try { ks = KeyStore.getInstance(storetype); } catch (KeyStoreException e) { throw new SignerException("keystore type '" + storetype + "' is not supported", e); } if (!keystore.exists()) { throw new SignerException("The keystore " + keystore + " couldn't be found"); } FileInputStream in = null; try { in = new FileInputStream(keystore); ks.load(in, storepass != null ? storepass.toCharArray() : null); } catch (Exception e) { throw new SignerException("Unable to load the keystore " + keystore, e); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { // ignore } } if (alias == null) { throw new SignerException("alias option must be set"); } try { chain = ks.getCertificateChain(alias); } catch (KeyStoreException e) { throw new SignerException(e.getMessage(), e); } if (chain == null) { throw new SignerException( "No certificate found under the alias '" + alias + "' in the keystore " + keystore); } char[] password = keypass != null ? keypass.toCharArray() : storepass.toCharArray(); try { privateKey = (PrivateKey) ks.getKey(alias, password); } catch (Exception e) { throw new SignerException("Failed to retrieve the private key from the keystore", e); } } else { // separate private key and certificate files (PVK/SPC) if (keyfile == null) { throw new SignerException("keyfile option must be set"); } if (!keyfile.exists()) { throw new SignerException("The keyfile " + keyfile + " couldn't be found"); } if (certfile == null) { throw new SignerException("certfile option must be set"); } if (!certfile.exists()) { throw new SignerException("The certfile " + certfile + " couldn't be found"); } // load the certificate chain try { chain = loadCertificateChain(certfile); } catch (Exception e) { throw new SignerException("Failed to load the certificate from " + certfile, e); } // load the private key try { privateKey = PVK.parse(keyfile, keypass); } catch (Exception e) { throw new SignerException("Failed to load the private key from " + keyfile, e); } } if (algorithm != null && DigestAlgorithm.of(algorithm) == null) { throw new SignerException("The digest algorithm " + algorithm + " is not supported"); } if (file == null) { throw new SignerException("missing file argument"); } if (!file.exists()) { throw new SignerException("The file " + file + " couldn't be found"); } PEFile peFile; try { peFile = new PEFile(file); } catch (IOException e) { throw new SignerException("Couldn't open the executable file " + file, e); } // and now the actual work! PESigner signer = new PESigner(chain, privateKey).withProgramName(name).withProgramURL(url) .withDigestAlgorithm(DigestAlgorithm.of(algorithm)) .withTimestamping(tsaurl != null || tsmode != null) .withTimestampingMode(TimestampingMode.of(tsmode)).withTimestampingAutority(tsaurl); try { System.out.println("Adding Authenticode signature to " + file); signer.sign(peFile); } catch (Exception e) { throw new SignerException("Couldn't sign " + file, e); } finally { try { peFile.close(); } catch (IOException e) { System.err.println("Couldn't close " + file); e.printStackTrace(System.err); } } } catch (ParseException e) { e.printStackTrace(); } }