Java Code Examples for java.security.cert.X509Certificate#getSubjectAlternativeNames()
The following examples show how to use
java.security.cert.X509Certificate#getSubjectAlternativeNames() .
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: X509Utils.java From bcm-android with GNU General Public License v3.0 | 7 votes |
/** * Returns either a string that "sums up" the certificate for humans, in a similar manner to what you might see * in a web browser, or null if one cannot be extracted. This will typically be the common name (CN) field, but * can also be the org (O) field, org+location+country if withLocation is set, or the email * address for S/MIME certificates. */ @Nullable public static String getDisplayNameFromCertificate(@Nonnull X509Certificate certificate, boolean withLocation) throws CertificateParsingException { X500Name name = new X500Name(certificate.getSubjectX500Principal().getName()); String commonName = null, org = null, location = null, country = null; for (RDN rdn : name.getRDNs()) { AttributeTypeAndValue pair = rdn.getFirst(); String val = ((ASN1String) pair.getValue()).getString(); ASN1ObjectIdentifier type = pair.getType(); if (type.equals(RFC4519Style.cn)) commonName = val; else if (type.equals(RFC4519Style.o)) org = val; else if (type.equals(RFC4519Style.l)) location = val; else if (type.equals(RFC4519Style.c)) country = val; } final Collection<List<?>> subjectAlternativeNames = certificate.getSubjectAlternativeNames(); String altName = null; if (subjectAlternativeNames != null) for (final List<?> subjectAlternativeName : subjectAlternativeNames) if ((Integer) subjectAlternativeName.get(0) == 1) // rfc822name altName = (String) subjectAlternativeName.get(1); if (org != null) { return withLocation ? Joiner.on(", ").skipNulls().join(org, location, country) : org; } else if (commonName != null) { return commonName; } else { return altName; } }
Example 2
Source File: TlsToolkitStandaloneTest.java From nifi with Apache License 2.0 | 6 votes |
@Test public void testStaticHostnameNoSan() throws Exception { String hostname = "static.nifi.apache.org"; runAndAssertExitCode(ExitCode.SUCCESS, "-o", tempDir.getAbsolutePath(), "-n", hostname); X509Certificate x509Certificate = checkLoadCertPrivateKey(TlsConfig.DEFAULT_KEY_PAIR_ALGORITHM); Certificate[] certificateChain = loadCertificateChain(hostname, x509Certificate); X509Certificate clientCert = (X509Certificate) certificateChain[0]; Collection<List<?>> clientSaNames = clientCert.getSubjectAlternativeNames(); // Must have one san that matches assertEquals(1, clientSaNames.size()); List<?> firstSan = clientSaNames.toArray(new List<?>[0])[0]; assertEquals(GeneralName.dNSName, firstSan.get(0)); assertEquals(hostname, firstSan.get(1)); }
Example 3
Source File: OkHostnameVerifier.java From CordovaYoutubeVideoPlayer with MIT License | 5 votes |
private List<String> getSubjectAltNames(X509Certificate certificate, int type) { List<String> result = new ArrayList<String>(); try { Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames(); if (subjectAltNames == null) { return Collections.emptyList(); } for (Object subjectAltName : subjectAltNames) { List<?> entry = (List<?>) subjectAltName; if (entry == null || entry.size() < 2) { continue; } Integer altNameType = (Integer) entry.get(0); if (altNameType == null) { continue; } if (altNameType == type) { String altName = (String) entry.get(1); if (altName != null) { result.add(altName); } } } return result; } catch (CertificateParsingException e) { return Collections.emptyList(); } }
Example 4
Source File: OkHostnameVerifier.java From bluemix-parking-meter with MIT License | 5 votes |
private List<String> getSubjectAltNames(X509Certificate certificate, int type) { List<String> result = new ArrayList<String>(); try { Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames(); if (subjectAltNames == null) { return Collections.emptyList(); } for (Object subjectAltName : subjectAltNames) { List<?> entry = (List<?>) subjectAltName; if (entry == null || entry.size() < 2) { continue; } Integer altNameType = (Integer) entry.get(0); if (altNameType == null) { continue; } if (altNameType == type) { String altName = (String) entry.get(1); if (altName != null) { result.add(altName); } } } return result; } catch (CertificateParsingException e) { return Collections.emptyList(); } }
Example 5
Source File: OkHostnameVerifier.java From reader with MIT License | 5 votes |
private List<String> getSubjectAltNames(X509Certificate certificate, int type) { List<String> result = new ArrayList<String>(); try { Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames(); if (subjectAltNames == null) { return Collections.emptyList(); } for (Object subjectAltName : subjectAltNames) { List<?> entry = (List<?>) subjectAltName; if (entry == null || entry.size() < 2) { continue; } Integer altNameType = (Integer) entry.get(0); if (altNameType == null) { continue; } if (altNameType == type) { String altName = (String) entry.get(1); if (altName != null) { result.add(altName); } } } return result; } catch (CertificateParsingException e) { return Collections.emptyList(); } }
Example 6
Source File: OpenSslCertManagerTest.java From strimzi-kafka-operator with Apache License 2.0 | 5 votes |
private void testGenerateSelfSignedCert(File key, File cert, File trustStore, String trustStorePassword, Subject sbj) throws Exception { ssl.generateSelfSignedCert(key, cert, sbj, 365); ssl.addCertToTrustStore(cert, "ca", trustStore, trustStorePassword); Certificate c = certFactory.generateCertificate(new FileInputStream(cert)); c.verify(c.getPublicKey()); // subject verification if provided if (sbj != null) { if (c instanceof X509Certificate) { X509Certificate x509Certificate = (X509Certificate) c; Principal p = x509Certificate.getSubjectDN(); assertThat(String.format("CN=%s, O=%s", sbj.commonName(), sbj.organizationName()), is(p.getName())); if (sbj.subjectAltNames() != null && sbj.subjectAltNames().size() > 0) { final Collection<List<?>> sans = x509Certificate.getSubjectAlternativeNames(); assertThat(sans, is(notNullValue())); assertThat(sbj.subjectAltNames().size(), is(sans.size())); for (final List<?> sanItem : sans) { assertThat(sbj.subjectAltNames().containsValue(sanItem.get(1)), is(true)); } } } else { fail(); } } // truststore verification if provided if (trustStore != null) { KeyStore store = KeyStore.getInstance("PKCS12"); store.load(new FileInputStream(trustStore), trustStorePassword.toCharArray()); X509Certificate storeCert = (X509Certificate) store.getCertificate("ca"); storeCert.verify(storeCert.getPublicKey()); } }
Example 7
Source File: OkHostnameVerifier.java From crosswalk-cordova-android with Apache License 2.0 | 5 votes |
private List<String> getSubjectAltNames(X509Certificate certificate, int type) { List<String> result = new ArrayList<String>(); try { Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames(); if (subjectAltNames == null) { return Collections.emptyList(); } for (Object subjectAltName : subjectAltNames) { List<?> entry = (List<?>) subjectAltName; if (entry == null || entry.size() < 2) { continue; } Integer altNameType = (Integer) entry.get(0); if (altNameType == null) { continue; } if (altNameType == type) { String altName = (String) entry.get(1); if (altName != null) { result.add(altName); } } } return result; } catch (CertificateParsingException e) { return Collections.emptyList(); } }
Example 8
Source File: OkHostnameVerifier.java From nv-websocket-client with Apache License 2.0 | 5 votes |
private static List<String> getSubjectAltNames(X509Certificate certificate, int type) { List<String> result = new ArrayList<String>(); try { Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames(); if (subjectAltNames == null) { return Collections.emptyList(); } for (Object subjectAltName : subjectAltNames) { List<?> entry = (List<?>) subjectAltName; if (entry == null || entry.size() < 2) { continue; } Integer altNameType = (Integer) entry.get(0); if (altNameType == null) { continue; } if (altNameType == type) { String altName = (String) entry.get(1); if (altName != null) { result.add(altName); } } } return result; } catch (CertificateParsingException e) { return Collections.emptyList(); } }
Example 9
Source File: OkHostnameVerifier.java From AndroidProjects with MIT License | 5 votes |
private static List<String> getSubjectAltNames(X509Certificate certificate, int type) { List<String> result = new ArrayList<>(); try { Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames(); if (subjectAltNames == null) { return Collections.emptyList(); } for (Object subjectAltName : subjectAltNames) { List<?> entry = (List<?>) subjectAltName; if (entry == null || entry.size() < 2) { continue; } Integer altNameType = (Integer) entry.get(0); if (altNameType == null) { continue; } if (altNameType == type) { String altName = (String) entry.get(1); if (altName != null) { result.add(altName); } } } return result; } catch (CertificateParsingException e) { return Collections.emptyList(); } }
Example 10
Source File: SdsX509TrustManager.java From grpc-java with Apache License 2.0 | 5 votes |
private static void verifySubjectAltNameInLeaf(X509Certificate cert, List<String> verifyList) throws CertificateException { Collection<List<?>> names = cert.getSubjectAlternativeNames(); if (names == null || names.isEmpty()) { throw new CertificateException("Peer certificate SAN check failed"); } for (List<?> name : names) { if (verifyOneSanInList(name, verifyList)) { return; } } // at this point there's no match throw new CertificateException("Peer certificate SAN check failed"); }
Example 11
Source File: XmppHostnameVerifier.java From Smack with Apache License 2.0 | 5 votes |
/** * Check if the certificate allows use of the given IP address. * <p> * From RFC2818 ยง 3.1: "In some cases, the URI is specified as an IP address rather than a * hostname. In this case, the iPAddress subjectAltName must be present in the certificate and * must exactly match the IP in the URI." * <p> * * @param expectedIP TODO javadoc me please * @param cert TODO javadoc me please * @throws CertificateException */ private static void matchIp(String expectedIP, X509Certificate cert) throws CertificateException { Collection<List<?>> subjectAlternativeNames = cert.getSubjectAlternativeNames(); if (subjectAlternativeNames == null) { throw new CertificateException("No subject alternative names present"); } List<String> nonMatchingIpAltnames = new LinkedList<>(); for (List<?> san : subjectAlternativeNames) { if (((Integer) san.get(0)).intValue() != ALTNAME_IP) { continue; } String ipAddress = (String) san.get(1); if (expectedIP.equalsIgnoreCase(ipAddress)) { return; } else { try { // See if the addresses match if we transform then, useful for IPv6 addresses if (InetAddress.getByName(expectedIP).equals(InetAddress.getByName(ipAddress))) { // expectedIP matches the given ipAddress, return return; } } catch (UnknownHostException | SecurityException e) { LOGGER.log(Level.FINE, "Comparing IP strings failed", e); } } nonMatchingIpAltnames.add(ipAddress); } StringBuilder sb = new StringBuilder("No subject alternative names matching IP address " + expectedIP + " found. Tried: "); for (String s : nonMatchingIpAltnames) { sb.append(s).append(','); } throw new CertificateException(sb.toString()); }
Example 12
Source File: MemorizingTrustManager.java From Pix-Art-Messenger with GNU General Public License v3.0 | 5 votes |
private String hostNameMessage(X509Certificate cert, String hostname) { StringBuffer si = new StringBuffer(); si.append(master.getString(R.string.mtm_hostname_mismatch, hostname)); si.append("\n\n"); try { Collection<List<?>> sans = cert.getSubjectAlternativeNames(); if (sans == null) { si.append(cert.getSubjectDN()); si.append("\n"); } else for (List<?> altName : sans) { Object name = altName.get(1); if (name instanceof String) { si.append("["); si.append((Integer) altName.get(0)); si.append("] "); si.append(name); si.append("\n"); } } } catch (CertificateParsingException e) { e.printStackTrace(); si.append("<Parsing error: "); si.append(e.getLocalizedMessage()); si.append(">\n"); } si.append("\n"); si.append(master.getString(R.string.mtm_connect_anyway)); si.append("\n\n"); si.append(master.getString(R.string.mtm_cert_details)); certDetails(si, cert); return si.toString(); }
Example 13
Source File: OkHostnameVerifier.java From iGap-Android with GNU Affero General Public License v3.0 | 5 votes |
private static List<String> getSubjectAltNames(X509Certificate certificate, int type) { List<String> result = new ArrayList<String>(); try { Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames(); if (subjectAltNames == null) { return Collections.emptyList(); } for (Object subjectAltName : subjectAltNames) { List<?> entry = (List<?>) subjectAltName; if (entry == null || entry.size() < 2) { continue; } Integer altNameType = (Integer) entry.get(0); if (altNameType == null) { continue; } if (altNameType == type) { String altName = (String) entry.get(1); if (altName != null) { result.add(altName); } } } return result; } catch (CertificateParsingException e) { return Collections.emptyList(); } }
Example 14
Source File: CryptoHelper.java From Conversations with GNU General Public License v3.0 | 5 votes |
public static Pair<Jid, String> extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, IllegalArgumentException, CertificateParsingException { Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames(); List<String> emails = new ArrayList<>(); if (alternativeNames != null) { for (List<?> san : alternativeNames) { Integer type = (Integer) san.get(0); if (type == 1) { emails.add((String) san.get(1)); } } } X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject(); if (emails.size() == 0 && x500name.getRDNs(BCStyle.EmailAddress).length > 0) { emails.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.EmailAddress)[0].getFirst().getValue())); } String name = x500name.getRDNs(BCStyle.CN).length > 0 ? IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[0].getFirst().getValue()) : null; if (emails.size() >= 1) { return new Pair<>(Jid.of(emails.get(0)), name); } else if (name != null) { try { Jid jid = Jid.of(name); if (jid.isBareJid() && jid.getLocal() != null) { return new Pair<>(jid, null); } } catch (IllegalArgumentException e) { return null; } } return null; }
Example 15
Source File: OkHostnameVerifier.java From wildfly-samples with MIT License | 5 votes |
private List<String> getSubjectAltNames(X509Certificate certificate, int type) { List<String> result = new ArrayList<String>(); try { Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames(); if (subjectAltNames == null) { return Collections.emptyList(); } for (Object subjectAltName : subjectAltNames) { List<?> entry = (List<?>) subjectAltName; if (entry == null || entry.size() < 2) { continue; } Integer altNameType = (Integer) entry.get(0); if (altNameType == null) { continue; } if (altNameType == type) { String altName = (String) entry.get(1); if (altName != null) { result.add(altName); } } } return result; } catch (CertificateParsingException e) { return Collections.emptyList(); } }
Example 16
Source File: TlsToolkitStandaloneTest.java From nifi with Apache License 2.0 | 5 votes |
@Test public void testDynamicHostnameDynamicSansSameRange() throws Exception { String nodeNames = "node[1-2].nifi.apache.org"; String saNames = "alternative[1-2].nifi.apache.org"; runAndAssertExitCode(ExitCode.SUCCESS, "-o", tempDir.getAbsolutePath(), "-n", nodeNames, "--subjectAlternativeName", saNames); X509Certificate x509Certificate = checkLoadCertPrivateKey(TlsConfig.DEFAULT_KEY_PAIR_ALGORITHM); Stream<InstanceIdentifier> hostIds = InstanceIdentifier.createIdentifiers(Arrays.stream(new String[]{nodeNames})); Stream<InstanceIdentifier> sansIds = InstanceIdentifier.createIdentifiers(Arrays.stream(new String[]{saNames})); String[] nodeHosts = hostIds.map(InstanceIdentifier::getHostname).toArray(String[]::new); String[] sanHosts = sansIds.map(InstanceIdentifier::getHostname).toArray(String[]::new); assertEquals(nodeHosts.length, sanHosts.length); for (int i = 0; i< nodeHosts.length; i++) { String host = nodeHosts[i]; String san = sanHosts[i]; Certificate[] certificateChain = loadCertificateChain(host, x509Certificate); X509Certificate clientCert = (X509Certificate) certificateChain[0]; Collection<List<?>> clientSaNames = clientCert.getSubjectAlternativeNames(); // Must have two sans, and both must match assertEquals(2, clientSaNames.size()); List<?> hostSan = clientSaNames.toArray(new List<?>[0])[0]; assertEquals(GeneralName.dNSName, hostSan.get(0)); assertEquals(host, hostSan.get(1)); List<?> altSan = clientSaNames.toArray(new List<?>[0])[1]; assertEquals(GeneralName.dNSName, altSan.get(0)); assertEquals(san, altSan.get(1)); } }
Example 17
Source File: SANCertificateIdentityMapping.java From Openfire with Apache License 2.0 | 4 votes |
/** * Returns the JID representation of an XMPP entity contained as a SubjectAltName extension * in the certificate. If none was found then return an empty list. * * @param certificate the certificate presented by the remote entity. * @return the JID representation of an XMPP entity contained as a SubjectAltName extension * in the certificate. If none was found then return an empty list. */ @Override public List<String> mapIdentity( X509Certificate certificate ) { List<String> identities = new ArrayList<>(); try { Collection<List<?>> altNames = certificate.getSubjectAlternativeNames(); // Check that the certificate includes the SubjectAltName extension if ( altNames == null ) { return Collections.emptyList(); } for ( List<?> item : altNames ) { final Integer type = (Integer) item.get( 0 ); final Object value = item.get( 1 ); // this is either a string, or a byte-array that represents the ASN.1 DER encoded form. final String result; switch ( type ) { case 0: // OtherName: search for "id-on-xmppAddr" or 'sRVName' or 'userPrincipalName' result = parseOtherName( (byte[]) value ); break; case 2: // DNS result = (String) value; break; case 6: // URI result = (String) value; break; default: // Not applicable to XMPP, so silently ignore them result = null; break; } if ( result != null ) { identities.add( result ); } } } catch ( CertificateParsingException e ) { Log.error( "Error parsing SubjectAltName in certificate: " + certificate.getSubjectDN(), e ); } return identities; }
Example 18
Source File: ServerTrustManager.java From AndroidPNClient with Apache License 2.0 | 4 votes |
/** * Returns the JID representation of an XMPP entity contained as a SubjectAltName extension * in the certificate. If none was found then return <tt>null</tt>. * * @param certificate the certificate presented by the remote entity. * @return the JID representation of an XMPP entity contained as a SubjectAltName extension * in the certificate. If none was found then return <tt>null</tt>. */ private static List<String> getSubjectAlternativeNames(X509Certificate certificate) { List<String> identities = new ArrayList<String>(); try { Collection<List<?>> altNames = certificate.getSubjectAlternativeNames(); // Check that the certificate includes the SubjectAltName extension if (altNames == null) { return Collections.emptyList(); } // Use the type OtherName to search for the certified server name /*for (List item : altNames) { Integer type = (Integer) item.get(0); if (type == 0) { // Type OtherName found so return the associated value try { // Value is encoded using ASN.1 so decode it to get the server's identity ASN1InputStream decoder = new ASN1InputStream((byte[]) item.toArray()[1]); DEREncodable encoded = decoder.readObject(); encoded = ((DERSequence) encoded).getObjectAt(1); encoded = ((DERTaggedObject) encoded).getObject(); encoded = ((DERTaggedObject) encoded).getObject(); String identity = ((DERUTF8String) encoded).getString(); // Add the decoded server name to the list of identities identities.add(identity); } catch (UnsupportedEncodingException e) { // Ignore } catch (IOException e) { // Ignore } catch (Exception e) { e.printStackTrace(); } } // Other types are not good for XMPP so ignore them System.out.println("SubjectAltName of invalid type found: " + certificate); }*/ } catch (CertificateParsingException e) { e.printStackTrace(); } return identities; }
Example 19
Source File: XmppDomainVerifier.java From Pix-Art-Messenger with GNU General Public License v3.0 | 4 votes |
@Override public boolean verify(String domain, String hostname, SSLSession sslSession) { try { Certificate[] chain = sslSession.getPeerCertificates(); if (chain.length == 0 || !(chain[0] instanceof X509Certificate)) { return false; } X509Certificate certificate = (X509Certificate) chain[0]; final List<String> commonNames = getCommonNames(certificate); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isSelfSigned(certificate)) { if (commonNames.size() == 1 && matchDomain(domain, commonNames)) { Log.d(LOGTAG, "accepted CN in self signed cert as work around for " + domain); return true; } } Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames(); List<String> xmppAddrs = new ArrayList<>(); List<String> srvNames = new ArrayList<>(); List<String> domains = new ArrayList<>(); if (alternativeNames != null) { for (List<?> san : alternativeNames) { final Integer type = (Integer) san.get(0); if (type == 0) { final Pair<String, String> otherName = parseOtherName((byte[]) san.get(1)); if (otherName != null && otherName.first != null && otherName.second != null) { switch (otherName.first) { case SRV_NAME: srvNames.add(otherName.second.toLowerCase(Locale.US)); break; case XMPP_ADDR: xmppAddrs.add(otherName.second.toLowerCase(Locale.US)); break; default: Log.d(LOGTAG, "oid: " + otherName.first + " value: " + otherName.second); } } } else if (type == 2) { final Object value = san.get(1); if (value instanceof String) { domains.add(((String) value).toLowerCase(Locale.US)); } } } } if (srvNames.size() == 0 && xmppAddrs.size() == 0 && domains.size() == 0) { domains.addAll(commonNames); } Log.d(LOGTAG, "searching for " + domain + " in srvNames: " + srvNames + " xmppAddrs: " + xmppAddrs + " domains:" + domains); if (hostname != null) { Log.d(LOGTAG, "also trying to verify hostname " + hostname); } return xmppAddrs.contains(domain) || srvNames.contains("_xmpp-client." + domain) || matchDomain(domain, domains) || (hostname != null && matchDomain(hostname, domains)); } catch (Exception e) { return false; } }
Example 20
Source File: MySqlHostVerifier.java From r2dbc-mysql with Apache License 2.0 | 4 votes |
private static List<San> extractSans(X509Certificate cert) { try { Collection<List<?>> pairs = cert.getSubjectAlternativeNames(); if (pairs == null || pairs.isEmpty()) { return Collections.emptyList(); } List<San> sans = new ArrayList<>(); for (List<?> pair : pairs) { // Ignore if it is not a pair. if (pair == null || pair.size() < 2) { continue; } Integer type = determineSubjectType(pair.get(0)); if (type == null) { continue; } if (San.DNS == type || San.IP == type) { Object value = pair.get(1); if (value instanceof String) { sans.add(new San((String) value, type)); } else if (value instanceof byte[]) { // TODO: decode ASN.1 DER form. logger.warn("Certificate contains an ASN.1 DER encoded form in Subject Alternative Names, but DER is unsupported now"); } else if (logger.isWarnEnabled()) { logger.warn("Certificate contains an unknown value of Subject Alternative Names: {}", value.getClass()); } } else { logger.warn("Certificate contains an unknown type of Subject Alternative Names: {}", type); } } return sans; } catch (CertificateParsingException ignored) { return Collections.emptyList(); } }