List of usage examples for java.security.cert X509Certificate getSubjectDN
public abstract Principal getSubjectDN();
From source file:eu.europa.ejusticeportal.dss.applet.model.token.CertificateDisplayUtils.java
/** * Get the information from the certificate to allow it to be displayed in human readable form. * /*from www . j a v a2 s . c o m*/ * @param keyEntry the DSSPrivateKeyEntry * @return the CertificateDisplayName */ public static CertificateDisplayDetails getDisplayDetails(DSSPrivateKeyEntry keyEntry, CardProfile cp) { final X509Certificate cert = (X509Certificate) keyEntry.getCertificate(); String subjectDN = cert.getSubjectDN().getName(); Map<String, String> parts = parseLdapName(subjectDN); if (parts.get("CN") != null) { subjectDN = parts.get("CN"); } String issuerDN = cert.getIssuerX500Principal() == null ? "" : cert.getIssuerX500Principal().getName(); parts = parseLdapName(issuerDN); String issuerCountry = parts.get("C") == null ? "" : parts.get("C"); String issuerName = parts.get("CN") == null ? "" : parts.get("CN"); if (parts.get("O") != null) { issuerName += ", " + parts.get("O"); } String serialNumber = formatSerialNumber(cert.getSerialNumber()); CertificateDisplayDetails cdd = new CertificateDisplayDetails(subjectDN, issuerName, issuerCountry, serialNumber, digest(cert), qualified(cert), sscd(cert), cert.getKeyUsage(), cert, cp, extensions(cert)); //check the expiration/start date valid(cdd); cdd.setSummaryInfo(summaryInfo(subjectDN, issuerName, issuerCountry, serialNumber, cdd.getStartDate(), cdd.getExpirationDate())); return cdd; }
From source file:com.dbay.apns4j.tools.ApnsTools.java
public final static SocketFactory createSocketFactory(InputStream keyStore, String password, String keystoreType, String algorithm, String protocol) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException, CertificateExpiredException { char[] pwdChars = password.toCharArray(); KeyStore ks = KeyStore.getInstance(keystoreType); ks.load(keyStore, pwdChars);/*from ww w.j av a 2 s . c om*/ // ?? Enumeration<String> enums = ks.aliases(); String alias = ""; if (enums.hasMoreElements()) { alias = enums.nextElement(); } if (StringUtils.isNotEmpty(alias)) { X509Certificate certificate = (X509Certificate) ks.getCertificate(alias); if (null != certificate) { String type = certificate.getType(); int ver = certificate.getVersion(); String name = certificate.getSubjectDN().getName(); String serialNumber = certificate.getSerialNumber().toString(16); String issuerDN = certificate.getIssuerDN().getName(); String sigAlgName = certificate.getSigAlgName(); String publicAlgorithm = certificate.getPublicKey().getAlgorithm(); Date before = certificate.getNotBefore(); Date after = certificate.getNotAfter(); String beforeStr = DateFormatUtils.format(before, "yyyy-MM-dd HH:mm:ss"); String afterStr = DateFormatUtils.format(after, "yyyy-MM-dd HH:mm:ss"); // ?? long expire = DateUtil.getNumberOfDaysBetween(new Date(), after); if (expire <= 0) { if (LOG.isErrorEnabled()) { LOG.error( "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]", name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr, afterStr, Math.abs(expire)); } throw new CertificateExpiredException("??[" + Math.abs(expire) + "]"); } if (LOG.isInfoEnabled()) { LOG.info( "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]?", name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr, afterStr, expire); } } } KeyManagerFactory kf = KeyManagerFactory.getInstance(algorithm); kf.init(ks, pwdChars); TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init((KeyStore) null); SSLContext context = SSLContext.getInstance(protocol); context.init(kf.getKeyManagers(), tmf.getTrustManagers(), null); return context.getSocketFactory(); }
From source file:nl.nn.adapterframework.http.AuthSSLProtocolSocketFactoryBase.java
protected static KeyStore createKeyStore(final URL url, final String password, String keyStoreType, String prefix) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { if (url == null) { throw new IllegalArgumentException("Keystore url for " + prefix + " may not be null"); }/*w w w .j a v a 2 s. c om*/ log.info("Initializing keystore for " + prefix + " from " + url.toString()); KeyStore keystore = KeyStore.getInstance(keyStoreType); keystore.load(url.openStream(), password != null ? password.toCharArray() : null); if (log.isInfoEnabled()) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); log.info(prefix + " '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; log.info(" Subject DN: " + cert.getSubjectDN()); log.info(" Signature Algorithm: " + cert.getSigAlgName()); log.info(" Valid from: " + cert.getNotBefore()); log.info(" Valid until: " + cert.getNotAfter()); log.info(" Issuer: " + cert.getIssuerDN()); } } } return keystore; }
From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java
/** * Given a certificate signing request, produce a signed certificate. * * @param caKey/*from ww w.j av a2s . c om*/ * @param caCert * @param r * @param makeAuthority * @return */ public static X509Certificate fulfillCertRequest(PrivateKey caKey, X509Certificate caCert, PKCS10CertificationRequest r, boolean makeAuthority) { X509v3CertificateBuilder b = new JcaX509v3CertificateBuilder(new X500Name(caCert.getSubjectDN().getName()), // the order of O,OU,CN returned is very important BigInteger.probablePrime(128, new SecureRandom()), Date.from(Instant.now().minusSeconds(1)), Date.from(LocalDateTime.now().plusYears(3).toInstant(ZoneOffset.UTC)), r.getSubject(), getPublicKeyFromInfo(r.getSubjectPublicKeyInfo())); try { b.addExtension(Extension.basicConstraints, true, new BasicConstraints(makeAuthority)); } catch (CertIOException ex) { Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex); } try { ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider("BC").build(caKey); X509CertificateHolder build = b.build(signer); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(build); } catch (OperatorCreationException | CertificateException ex) { Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex); return null; } }
From source file:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java
private static final void importCertificate(final String url, final KeyStore trustStore) throws Exception { final URL url2 = new URL(url); final SSLContext sslContext = SSLContext.getInstance("TLS"); final TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); final X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0]; final SavingTrustManager trustManager = new SavingTrustManager(defaultTrustManager); sslContext.init(null, new TrustManager[] { trustManager }, null); final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(url2.getHost(), url2.getPort() > 0 ? url2.getPort() : 443); socket.setSoTimeout(10000);/*from w w w. j a v a 2s. c om*/ try { socket.startHandshake(); socket.close(); } catch (SSLException e) { } final X509Certificate[] chain = trustManager.chain; if (chain == null) { LOGGER.error("Could not obtain server certificate chain from: " + url); return; } final MessageDigest sha1 = MessageDigest.getInstance("SHA1"); final MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { final X509Certificate cert = chain[i]; final String alias = url2.getHost() + "-" + (i + 1); if (!trustStore.containsAlias(alias)) { sha1.update(cert.getEncoded()); md5.update(cert.getEncoded()); LOGGER.trace("Importing certificate to trusted keystore >> " + "Subject: " + cert.getSubjectDN() + ", Issuer: " + cert.getIssuerDN() + ", SHA1: " + printHexBinary(sha1.digest()) + ", MD5: " + printHexBinary(md5.digest()) + ", Alias: " + alias); trustStore.setCertificateEntry(alias, cert); } } }
From source file:ch.bfh.unicert.certimport.Main.java
/** * Create a certificate fot the given CSV record * * @param record the record to parse/*from w w w . j a va2s. c o m*/ * @throws InvalidNameException */ private static void createCertificate(CSVRecord record) throws InvalidNameException { int recordid = Integer.parseInt(record.get(0)); String pemCert = record.get(1); String institution = record.get(2); int revoked = Integer.parseInt(record.get(3)); if (revoked == 1) { System.out.println("Certficate " + recordid + " is revoked. Looking for next certificate..."); return; } String studyBranch = record.get(5); String uniqueId = record.get(6); String mail = record.get(8); CertificateFactory cf; X509Certificate cert; try { cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(pemCert.getBytes())); } catch (CertificateException ex) { logger.log(Level.SEVERE, "Not able to read certificate for record {0}, exception: {1}", new Object[] { recordid, ex }); return; } DSAPublicKey pubKey = (DSAPublicKey) cert.getPublicKey(); String commonName = cert.getSubjectDN().getName(); LdapName ln = new LdapName(cert.getSubjectX500Principal().toString()); for (Rdn rdn : ln.getRdns()) { if (rdn.getType().equalsIgnoreCase("CN")) { commonName = (String) rdn.getValue(); break; } else if (rdn.getType().equalsIgnoreCase("UID")) { uniqueId = (String) rdn.getValue(); break; } else if (rdn.getType().equalsIgnoreCase("OU")) { studyBranch = (String) rdn.getValue(); break; } } IdentityData idData = new IdentityData(commonName, uniqueId, institution, studyBranch, null, null, null, null, null, "SwitchAAI", null); try { Certificate certificate = issuer.createClientCertificate(idData, keystorePath, pubKey, 10, "UniVote", new String[] { "Voter" }, uniBoardWSDLurl, uniBoardUrl, section); counter++; System.out.println("Certificate published for " + recordid + ". Count " + counter + " of 6424"); } catch (CertificateCreationException ex) { logger.log(Level.SEVERE, "Not able to create certificate for record {0}, exception: {1}", new Object[] { recordid, ex }); } }
From source file:org.dspace.authenticate.X509Authentication.java
/** * Return the email address from <code>certificate</code>, or null if an * email address cannot be found in the certificate. * <p>/* w w w. ja va 2s . c o m*/ * Note that the certificate parsing has only been tested with certificates * granted by the MIT Certification Authority, and may not work elsewhere. * * @param certificate - * An X509 certificate object * @return - The email address found in certificate, or null if an email * address cannot be found in the certificate. */ private static String getEmail(X509Certificate certificate) throws SQLException { Principal principal = certificate.getSubjectDN(); if (principal == null) { return null; } String dn = principal.getName(); if (dn == null) { return null; } StringTokenizer tokenizer = new StringTokenizer(dn, ","); String token = null; while (tokenizer.hasMoreTokens()) { int len = "emailaddress=".length(); token = (String) tokenizer.nextToken(); if (token.toLowerCase().startsWith("emailaddress=")) { // Make sure the token actually contains something if (token.length() <= len) { return null; } return token.substring(len).toLowerCase(); } } return null; }
From source file:com.xwiki.authentication.sts.STSTokenValidator.java
/** * validateSubjectDN(SignableSAMLObject samlToken, String subjectName) * Validates the subject (subject distinguished name) value from the certificate. * @param samlToken SignableSAMLObject saml Token * @param subjectName subjectNamme name to Validate * @return boolean valid => true, not valid => false *///from w ww .j a va2 s . c o m private static boolean validateSubjectDN(SignableSAMLObject samlToken, String subjectName) throws UnmarshallingException, ValidationException, CertificateException { Signature signature = samlToken.getSignature(); KeyInfo keyInfo = signature.getKeyInfo(); X509Certificate pubKey = KeyInfoHelper.getCertificates(keyInfo).get(0); String subjectDN = pubKey.getSubjectDN().getName(); log.trace("passed subjectName: '" + subjectName + "' certificate SubjectDN: '" + subjectDN); return subjectDN.equals(subjectName); }
From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java
public static String getCommonName(X509Certificate requestCertificate) { String distinguishedName = requestCertificate.getSubjectDN().getName(); if (distinguishedName != null && !distinguishedName.isEmpty()) { String[] dnSplits = distinguishedName.split(","); for (String dnSplit : dnSplits) { if (dnSplit.contains("CN=")) { String[] cnSplits = dnSplit.split("="); if (cnSplits[1] != null) { return cnSplits[1]; }//from ww w . j av a2s.c o m } } } return null; }
From source file:org.apache.nifi.registry.security.util.CertificateUtils.java
/** * Returns the DN extracted from the server certificate. * * @param socket the SSL Socket/*from w w w .j av a 2 s .c o m*/ * @return the extracted DN * @throws CertificateException if there is a problem parsing the certificate */ private static String extractPeerDNFromServerSSLSocket(Socket socket) throws CertificateException { String dn = null; if (socket instanceof SSLSocket) { final SSLSocket sslSocket = (SSLSocket) socket; try { final Certificate[] certChains = sslSocket.getSession().getPeerCertificates(); if (certChains != null && certChains.length > 0) { X509Certificate x509Certificate = convertAbstractX509Certificate(certChains[0]); dn = x509Certificate.getSubjectDN().getName().trim(); logger.debug("Extracted DN={} from server certificate", dn); } } catch (SSLPeerUnverifiedException e) { if (e.getMessage().equals(PEER_NOT_AUTHENTICATED_MSG)) { logger.error("The server did not present a certificate and thus the DN cannot" + " be extracted. Check that the other endpoint is providing a complete certificate chain"); } throw new CertificateException(e); } } return dn; }