public static KeyStore loadTrustStore(File certificateChainFile) throws IOException, GeneralSecurityException { KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); List<X509Certificate> certificateChain = readCertificateChain(certificateChainFile); for (X509Certificate certificate : certificateChain) { X500Principal principal = certificate.getSubjectX500Principal(); keyStore.setCertificateEntry(principal.getName("RFC2253"), certificate); } return keyStore; }
/** Returns true if {@code toVerify} was signed by {@code signingCert}'s public key. */ private boolean verifySignature(X509Certificate toVerify, X509Certificate signingCert) { if (!toVerify.getIssuerDN().equals(signingCert.getSubjectDN())) return false; try { toVerify.verify(signingCert.getPublicKey()); return true; } catch (GeneralSecurityException verifyFailed) { return false; } }
/** * Returns the {@code subject} (subject distinguished name) as an {@code * X500Principal}. * * @return the {@code subject} (subject distinguished name) */ public X500Principal getSubjectX500Principal() { try { // TODO if there is no X.509 certificate provider installed // should we try to access Harmony X509CertImpl via classForName? CertificateFactory factory = CertificateFactory .getInstance("X.509"); X509Certificate cert = (X509Certificate) factory .generateCertificate(new ByteArrayInputStream(getEncoded())); return cert.getSubjectX500Principal(); } catch (Exception e) { throw new RuntimeException("Failed to get X500Principal subject", e); } }
/** Returns the trusted CA certificate that signed {@code cert}. */ private X509Certificate findByIssuerAndSignature(X509Certificate cert) { X500Principal issuer = cert.getIssuerX500Principal(); Set<X509Certificate> subjectCaCerts = subjectToCaCerts.get(issuer); if (subjectCaCerts == null) return null; for (X509Certificate caCert : subjectCaCerts) { PublicKey publicKey = caCert.getPublicKey(); try { cert.verify(publicKey); return caCert; } catch (Exception ignored) { } } return null; }
private String describeCertificate( X509Certificate certificate ) { return "Subject: " + certificate.getSubjectDN() + ", Issuer: " + certificate.getIssuerDN(); }
/** * Populate the available server public keys into a local static HashMap. This method is not * thread safe. */ public static void initCertsMap(Properties props) throws Exception { certificateMap = new HashMap(); certificateFilePath = props.getProperty(PUBLIC_KEY_FILE_PROP); if (certificateFilePath != null && certificateFilePath.length() > 0) { KeyStore ks = KeyStore.getInstance("JKS"); String keyStorePass = props.getProperty(PUBLIC_KEY_PASSWD_PROP); char[] passPhrase = (keyStorePass != null ? keyStorePass.toCharArray() : null); FileInputStream keystorefile = new FileInputStream(certificateFilePath); try { ks.load(keystorefile, passPhrase); } finally { keystorefile.close(); } Enumeration aliases = ks.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate cert = ks.getCertificate(alias); if (cert instanceof X509Certificate) { String subject = ((X509Certificate) cert).getSubjectDN().getName(); certificateMap.put(subject, cert); } } } }
public class TestClass { public static void main(String[] args) throws Exception { KeyStore p12 = KeyStore.getInstance("pkcs12"); p12.load(new FileInputStream("pkcs.p12"), "password".toCharArray()); Enumeration e = p12.aliases(); while (e.hasMoreElements()) { String alias = (String) e.nextElement(); X509Certificate c = (X509Certificate) p12.getCertificate(alias); Principal subject = c.getSubjectDN(); String subjectArray[] = subject.toString().split(","); for (String s : subjectArray) { String[] str = s.trim().split("="); String key = str[0]; String value = str[1]; System.out.println(key + " - " + value); } } } }
TrustManagerFactory trustManagerFactory) throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); CertificateFactory cf = CertificateFactory.getInstance("X.509"); .generateCertificate(new ByteArrayInputStream(buf.array())); X500Principal principal = cert.getSubjectX500Principal(); ks.setCertificateEntry(principal.getName("RFC2253"), cert);
/** * 通过keystore获取私钥证书的certId值 * @param keyStore * @return */ private static String getCertIdIdByStore(KeyStore keyStore) { Enumeration<String> aliasenum = null; try { aliasenum = keyStore.aliases(); String keyAlias = null; if (aliasenum.hasMoreElements()) { keyAlias = aliasenum.nextElement(); } X509Certificate cert = (X509Certificate) keyStore .getCertificate(keyAlias); return cert.getSerialNumber().toString(); } catch (KeyStoreException e) { LogUtil.writeErrorLog("getCertIdIdByStore Error", e); return null; } }
private SSLContext createSSLContext(final SSLContextService service) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException { SSLContextBuilder builder = SSLContexts.custom(); final String trustFilename = service.getTrustStoreFile(); if (trustFilename != null) { final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType()); try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) { truststore.load(in, service.getTrustStorePassword().toCharArray()); } builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy()); } final String keyFilename = service.getKeyStoreFile(); if (keyFilename != null) { final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType()); try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) { keystore.load(in, service.getKeyStorePassword().toCharArray()); } builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray()); final String alias = keystore.aliases().nextElement(); final Certificate cert = keystore.getCertificate(alias); if (cert instanceof X509Certificate) { principal = ((X509Certificate) cert).getSubjectDN(); } } builder = builder.setProtocol(service.getSslAlgorithm()); final SSLContext sslContext = builder.build(); return sslContext; }
/** * Load the private key of the server. This method is not thread safe. */ public static void initPrivateKey(Properties props) throws Exception { String privateKeyFilePath = props.getProperty(PRIVATE_KEY_FILE_PROP); privateKeyAlias = ""; privateKeyEncrypt = null; if (privateKeyFilePath != null && privateKeyFilePath.length() > 0) { KeyStore ks = KeyStore.getInstance("PKCS12"); privateKeyAlias = props.getProperty(PRIVATE_KEY_ALIAS_PROP); if (privateKeyAlias == null) { privateKeyAlias = ""; } String keyStorePass = props.getProperty(PRIVATE_KEY_PASSWD_PROP); char[] passPhrase = (keyStorePass != null ? keyStorePass.toCharArray() : null); FileInputStream privateKeyFile = new FileInputStream(privateKeyFilePath); try { ks.load(privateKeyFile, passPhrase); } finally { privateKeyFile.close(); } Key key = ks.getKey(privateKeyAlias, passPhrase); Certificate keyCert = ks.getCertificate(privateKeyAlias); if (key instanceof PrivateKey && keyCert instanceof X509Certificate) { privateKeyEncrypt = (PrivateKey) key; privateKeySignAlgo = ((X509Certificate) keyCert).getSigAlgName(); privateKeySubject = ((X509Certificate) keyCert).getSubjectDN().getName(); } } }
FileInputStream is = new FileInputStream(new File(_serverCACertFile)); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null); CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE); int i = 0; while (is.available() > 0) { X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is); LOGGER.info("Read certificate serial number {} by issuer {} ", cert.getSerialNumber().toString(16), cert.getIssuerDN().toString());
public KeyStoreHelper(KeyStore ks, String password) throws Exception { Enumeration<String> en = ks.aliases(); while (en.hasMoreElements()) { String alias = en.nextElement(); Certificate cert = ks.getCertificate(alias); if (ks.isCertificateEntry(alias) && ! alias.startsWith(DUMMY_CERT_ALIAS)){ final KeyStore keyStore = createEmptyKeyStore(); keyStore.setCertificateEntry("cert-1", cert); if (ks.isKeyEntry(alias) && cert instanceof X509Certificate) { X509Certificate x509Cert = (X509Certificate) cert; Collection<List<?>> ans = x509Cert.getSubjectAlternativeNames(); List<String> domains = new ArrayList<>(); if (ans != null) { String dn = x509Cert.getSubjectX500Principal().getName(); domains.addAll(getX509CertificateCommonNames(dn)); if (!domains.isEmpty()) {
@Override public RealmIdentity getRealmIdentity(final Principal principal) throws RealmUnavailableException { if (principal instanceof NamePrincipal) { String name = principal.getName(); log.tracef("KeyStoreRealm: obtaining certificate by alias [%s]", name); return new KeyStoreRealmIdentity(name); final KeyStore keyStore = this.keyStore; try { final Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { final String alias = aliases.nextElement(); if (keyStore.isCertificateEntry(alias)) { final Certificate certificate = keyStore.getCertificate(alias); if (certificate instanceof X509Certificate && x500Principal.equals(X500PrincipalUtil.asX500Principal(((X509Certificate) certificate).getSubjectX500Principal()))) { log.tracef("KeyStoreRealm: certificate found by X500Principal in alias [%s]", alias); return new KeyStoreRealmIdentity(alias);
static List<X509Certificate> loadCertificates(KeyStore keyStore) { List<X509Certificate> certs = new LinkedList<>(); try { Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keyStore.isCertificateEntry(alias)) { X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); certs.add(cert); LOGGER.finest(() -> "Added certificate under alis " + alias + " for " + cert .getSubjectDN() + " to list of certificates"); } } } catch (KeyStoreException e) { throw new PkiException("Failed to load certificates from keystore: " + keyStore, e); } return certs; } }
public static KeyStore createKeyStore(InputStream certInputStream, InputStream keyInputStream, String clientKeyAlgo, char[] clientKeyPassphrase, String keyStoreFile, char[] keyStorePassphrase) throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException { CertificateFactory certFactory = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream); byte[] keyBytes = decodePem(keyInputStream); PrivateKey privateKey; KeyFactory keyFactory = KeyFactory.getInstance(clientKeyAlgo); try { // First let's try PKCS8 privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes)); } catch (InvalidKeySpecException e) { // Otherwise try PKCS8 RSAPrivateCrtKeySpec keySpec = PKCS1Util.decodePKCS1(keyBytes); privateKey = keyFactory.generatePrivate(keySpec); } KeyStore keyStore = KeyStore.getInstance("JKS"); if (Utils.isNotNullOrEmpty(keyStoreFile)){ keyStore.load(new FileInputStream(keyStoreFile), keyStorePassphrase); } else { loadDefaultKeyStoreFile(keyStore, keyStorePassphrase); } String alias = cert.getSubjectX500Principal().getName(); keyStore.setKeyEntry(alias, privateKey, clientKeyPassphrase, new Certificate[]{cert}); return keyStore; }
/** * Update a keystore with a CA certificate * * @param pTrustStore the keystore to update * @param pCaCert CA cert as PEM used for the trust store */ public static void updateWithCaPem(KeyStore pTrustStore, File pCaCert) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException { InputStream is = new FileInputStream(pCaCert); try { CertificateFactory certFactory = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(is); String alias = cert.getSubjectX500Principal().getName(); pTrustStore.setCertificateEntry(alias, cert); } finally { is.close(); } }
/** * Returns the {@code issuer} (issuer distinguished name) as an {@code * X500Principal}. * * @return the {@code issuer} (issuer distinguished name). */ public X500Principal getIssuerX500Principal() { try { // TODO if there is no X.509 certificate provider installed // should we try to access Harmony X509CertImpl via classForName? CertificateFactory factory = CertificateFactory .getInstance("X.509"); X509Certificate cert = (X509Certificate) factory .generateCertificate(new ByteArrayInputStream(getEncoded())); return cert.getIssuerX500Principal(); } catch (Exception e) { throw new RuntimeException("Failed to get X500Principal issuer", e); } }
InputStream certStream = new ByteArrayInputStream(rawCert); CertificateFactory certFactory = CertificateFactory.getInstance("X509"); X509Certificate x509Cert = (X509Certificate) certFactory.generateCertificate(certStream); sb.append("Certificate subject: " + x509Cert.getSubjectDN() + "<br>"); sb.append("Certificate issuer: " + x509Cert.getIssuerDN() + "<br>"); sb.append("Certificate serial number: " + x509Cert.getSerialNumber() + "<br>"); sb.append("<br>");
private static final X500Principal DEBUG_DN = new X500Principal("CN=Android Debug,O=Android,C=US"); private boolean isDebuggable(Context ctx) Signature signatures[] = pinfo.signatures; CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream stream = new ByteArrayInputStream(signatures[i].toByteArray()); X509Certificate cert = (X509Certificate) cf.generateCertificate(stream); debuggable = cert.getSubjectX500Principal().equals(DEBUG_DN); if (debuggable) break;