List of usage examples for java.security.cert X509Certificate getSubjectDN
public abstract Principal getSubjectDN();
From source file:de.duenndns.ssl.MemorizingTrustManager.java
private void certDetails(StringBuffer si, X509Certificate c) { SimpleDateFormat validityDateFormater = new SimpleDateFormat("yyyy-MM-dd"); si.append("\n"); si.append(c.getSubjectDN().toString()); si.append("\n"); si.append(validityDateFormater.format(c.getNotBefore())); si.append(" - "); si.append(validityDateFormater.format(c.getNotAfter())); si.append("\nSHA-256: "); si.append(certHash(c, "SHA-256")); si.append("\nSHA-1: "); si.append(certHash(c, "SHA-1")); si.append("\nSigned by: "); si.append(c.getIssuerDN().toString()); si.append("\n"); }
From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java
protected void checkValidity(X509Certificate cert) throws ProxyPathValidatorException { try {/*from w w w. jav a2 s.com*/ cert.checkValidity(); } catch (CertificateExpiredException e) { throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, cert, "Certificate " + cert.getSubjectDN().getName() + " expired."); } catch (CertificateNotYetValidException e) { throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, cert, "Certificate " + cert.getSubjectDN().getName() + " not yet valid."); } }
From source file:eu.europa.ec.markt.dss.validation.SignedDocumentValidator.java
/** * For level -XL, every certificates values contained in the ValidationContext (except the SigningCertificate) must * be in the CertificatesValues of the signature * /*from w w w .j a v a 2s .c o m*/ * @param ctx * @param certificates * @param signingCert * @return */ protected boolean everyCertificateValueAreThere(ValidationContext ctx, List<X509Certificate> certificates, X509Certificate signingCert) { for (CertificateAndContext neededCert : ctx.getNeededCertificates()) { /* We don't need the signing certificate in the XL values */ if (neededCert.getCertificate().equals(signingCert)) { continue; } LOG.info("Looking for the certificate ref of " + neededCert); boolean found = false; for (X509Certificate referencedCert : certificates) { LOG.info("Compare to " + referencedCert.getSubjectDN()); if (referencedCert.equals(neededCert.getCertificate())) { found = true; break; } } LOG.info("Cert " + (found ? " found" : " not found")); if (!found) { return false; } } return true; }
From source file:com.vmware.bdd.cli.http.DefaultTrustManager.java
@Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { String errorMsg = ""; InputStream in = null;/*from ww w.java 2 s .co m*/ OutputStream out = null; // load key store file try { char[] pwd = cliProperties.readKeyStorePwd(); File file = new File(KEY_STORE_FILE); if (file.exists() && file.isFile()) { keyStore.load(new FileInputStream(file), pwd); } else { //init an empty keystore keyStore.load(null, pwd); } // show certificate informations MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); String md5Fingerprint = ""; String sha1Fingerprint = ""; SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy/MM/dd"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; sha1.update(cert.getEncoded()); md5.update(cert.getEncoded()); md5Fingerprint = ByteArrayUtils.byteArrayToHexString(md5.digest()); sha1Fingerprint = ByteArrayUtils.byteArrayToHexString(sha1.digest()); if (keyStore.getCertificate(md5Fingerprint) != null) { if (i == chain.length - 1) { return; } else { continue; } } System.out.println(); System.out.println("Server Certificate"); System.out.println("================================================================"); System.out.println("Subject: " + cert.getSubjectDN()); System.out.println("Issuer: " + cert.getIssuerDN()); System.out.println("SHA Fingerprint: " + sha1Fingerprint); System.out.println("MD5 Fingerprint: " + md5Fingerprint); System.out.println("Issued on: " + dateFormate.format(cert.getNotBefore())); System.out.println("Expires on: " + dateFormate.format(cert.getNotAfter())); System.out.println("Signature: " + cert.getSignature()); System.out.println(); if (checkExpired(cert.getNotBefore(), cert.getNotAfter())) { throw new CertificateException("The security certificate has expired."); } ConsoleReader reader = new ConsoleReader(); // Set prompt message reader.setPrompt(Constants.PARAM_PROMPT_ADD_CERTIFICATE_MESSAGE); // Read user input String readMsg; if (RunWayConfig.getRunType().equals(RunWayConfig.RunType.MANUAL)) { readMsg = reader.readLine().trim(); } else { readMsg = "yes"; } if ("yes".equalsIgnoreCase(readMsg) || "y".equalsIgnoreCase(readMsg)) { { // add new certificate into key store file. keyStore.setCertificateEntry(md5Fingerprint, cert); out = new FileOutputStream(KEY_STORE_FILE); keyStore.store(out, pwd); CommonUtil.setOwnerOnlyReadWrite(KEY_STORE_FILE); // save keystore password cliProperties.saveKeyStorePwd(pwd); } } else { if (i == chain.length - 1) { throw new CertificateException("Could not find a valid certificate in the keystore."); } else { continue; } } } } catch (FileNotFoundException e) { errorMsg = "Cannot find the keystore file: " + e.getMessage(); } catch (NoSuchAlgorithmException e) { errorMsg = "SSL Algorithm not supported: " + e.getMessage(); } catch (IOException e) { e.printStackTrace(); errorMsg = "IO error: " + e.getMessage(); } catch (KeyStoreException e) { errorMsg = "Keystore error: " + e.getMessage(); } catch (ConfigurationException e) { errorMsg = "cli.properties access error: " + e.getMessage(); } finally { if (!CommandsUtils.isBlank(errorMsg)) { System.out.println(errorMsg); logger.error(errorMsg); } if (in != null) { try { in.close(); } catch (IOException e) { logger.warn("Input stream of serengeti.keystore close failed."); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.warn("Output stream of serengeti.keystore close failed."); } } } }
From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java
protected KeyMap cacheKeys(KeyStore ks, KeyInfoManager keyInfoManager) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException { KeyMap keys = new KeyMap(); // load and cache the keys for (Entry<String, KeyInformation> keyEntry : keyInfoManager.getKeyInfo().entrySet()) { String keyAlias = keyEntry.getKey(); KeyInformation keyInfo = keyInfoManager.getKeyInformation(keyAlias); String passwordStr = keyInfo != null ? keyInfo.getPassword() : null; // Null is an acceptable value (means no key) Key key = null;/*from w ww .j a v a 2 s . c o m*/ // Attempt to get the key key = ks.getKey(keyAlias, passwordStr == null ? null : passwordStr.toCharArray()); if (key != null) { keys.setKey(keyAlias, key); } // Key loaded if (logger.isDebugEnabled()) { logger.debug( "Retrieved key from keystore: \n" + " Location: " + getKeyStoreParameters().getLocation() + "\n" + " Provider: " + getKeyStoreParameters().getProvider() + "\n" + " Type: " + getKeyStoreParameters().getType() + "\n" + " Alias: " + keyAlias + "\n" + " Password?: " + (passwordStr != null)); Certificate[] certs = ks.getCertificateChain(keyAlias); if (certs != null) { logger.debug("Certificate chain '" + keyAlias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; logger.debug(" Certificate " + (c + 1) + ":"); logger.debug(" Subject DN: " + cert.getSubjectDN()); logger.debug(" Signature Algorithm: " + cert.getSigAlgName()); logger.debug(" Valid from: " + cert.getNotBefore()); logger.debug(" Valid until: " + cert.getNotAfter()); logger.debug(" Issuer: " + cert.getIssuerDN()); } } } } } return keys; }
From source file:android.net.http.CertificateChainValidator.java
/** * Performs the handshake and server certificates validation * @param sslSocket The secure connection socket * @param domain The website domain//from w w w .j a v a 2 s .c om * @return An SSL error object if there is an error and null otherwise */ public SslError doHandshakeAndValidateServerCertificates(HttpsConnection connection, SSLSocket sslSocket, String domain) throws SSLHandshakeException, IOException { ++sTotal; SSLContext sslContext = HttpsConnection.getContext(); if (sslContext == null) { closeSocketThrowException(sslSocket, "SSL context is null"); } X509Certificate[] serverCertificates = null; long sessionBeforeHandshakeLastAccessedTime = 0; byte[] sessionBeforeHandshakeId = null; SSLSession sessionAfterHandshake = null; synchronized (sslContext) { // get SSL session before the handshake SSLSession sessionBeforeHandshake = getSSLSession(sslContext, connection.getHost()); if (sessionBeforeHandshake != null) { sessionBeforeHandshakeLastAccessedTime = sessionBeforeHandshake.getLastAccessedTime(); sessionBeforeHandshakeId = sessionBeforeHandshake.getId(); } // start handshake, close the socket if we fail try { sslSocket.setUseClientMode(true); sslSocket.startHandshake(); } catch (IOException e) { closeSocketThrowException(sslSocket, e.getMessage(), "failed to perform SSL handshake"); } // retrieve the chain of the server peer certificates Certificate[] peerCertificates = sslSocket.getSession().getPeerCertificates(); if (peerCertificates == null || peerCertificates.length <= 0) { closeSocketThrowException(sslSocket, "failed to retrieve peer certificates"); } else { serverCertificates = new X509Certificate[peerCertificates.length]; for (int i = 0; i < peerCertificates.length; ++i) { serverCertificates[i] = (X509Certificate) (peerCertificates[i]); } // update the SSL certificate associated with the connection if (connection != null) { if (serverCertificates[0] != null) { connection.setCertificate(new SslCertificate(serverCertificates[0])); } } } // get SSL session after the handshake sessionAfterHandshake = getSSLSession(sslContext, connection.getHost()); } if (sessionBeforeHandshakeLastAccessedTime != 0 && sessionAfterHandshake != null && Arrays.equals(sessionBeforeHandshakeId, sessionAfterHandshake.getId()) && sessionBeforeHandshakeLastAccessedTime < sessionAfterHandshake.getLastAccessedTime()) { if (HttpLog.LOGV) { HttpLog.v("SSL session was reused: total reused: " + sTotalReused + " out of total of: " + sTotal); ++sTotalReused; } // no errors!!! return null; } // check if the first certificate in the chain is for this site X509Certificate currCertificate = serverCertificates[0]; if (currCertificate == null) { closeSocketThrowException(sslSocket, "certificate for this site is null"); } else { if (!DomainNameChecker.match(currCertificate, domain)) { String errorMessage = "certificate not for this host: " + domain; if (HttpLog.LOGV) { HttpLog.v(errorMessage); } sslSocket.getSession().invalidate(); return new SslError(SslError.SSL_IDMISMATCH, currCertificate); } } // // first, we validate the chain using the standard validation // solution; if we do not find any errors, we are done; if we // fail the standard validation, we re-validate again below, // this time trying to retrieve any individual errors we can // report back to the user. // try { synchronized (mDefaultTrustManager) { mDefaultTrustManager.checkServerTrusted(serverCertificates, "RSA"); // no errors!!! return null; } } catch (CertificateException e) { if (HttpLog.LOGV) { HttpLog.v("failed to pre-validate the certificate chain, error: " + e.getMessage()); } } sslSocket.getSession().invalidate(); SslError error = null; // we check the root certificate separately from the rest of the // chain; this is because we need to know what certificate in // the chain resulted in an error if any currCertificate = serverCertificates[serverCertificates.length - 1]; if (currCertificate == null) { closeSocketThrowException(sslSocket, "root certificate is null"); } // check if the last certificate in the chain (root) is trusted X509Certificate[] rootCertificateChain = { currCertificate }; try { synchronized (mDefaultTrustManager) { mDefaultTrustManager.checkServerTrusted(rootCertificateChain, "RSA"); } } catch (CertificateExpiredException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "root certificate has expired"; } if (HttpLog.LOGV) { HttpLog.v(errorMessage); } error = new SslError(SslError.SSL_EXPIRED, currCertificate); } catch (CertificateNotYetValidException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "root certificate not valid yet"; } if (HttpLog.LOGV) { HttpLog.v(errorMessage); } error = new SslError(SslError.SSL_NOTYETVALID, currCertificate); } catch (CertificateException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "root certificate not trusted"; } if (HttpLog.LOGV) { HttpLog.v(errorMessage); } return new SslError(SslError.SSL_UNTRUSTED, currCertificate); } // Then go through the certificate chain checking that each // certificate trusts the next and that each certificate is // within its valid date range. Walk the chain in the order // from the CA to the end-user X509Certificate prevCertificate = serverCertificates[serverCertificates.length - 1]; for (int i = serverCertificates.length - 2; i >= 0; --i) { currCertificate = serverCertificates[i]; // if a certificate is null, we cannot verify the chain if (currCertificate == null) { closeSocketThrowException(sslSocket, "null certificate in the chain"); } // verify if trusted by chain if (!prevCertificate.getSubjectDN().equals(currCertificate.getIssuerDN())) { String errorMessage = "not trusted by chain"; if (HttpLog.LOGV) { HttpLog.v(errorMessage); } return new SslError(SslError.SSL_UNTRUSTED, currCertificate); } try { currCertificate.verify(prevCertificate.getPublicKey()); } catch (GeneralSecurityException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "not trusted by chain"; } if (HttpLog.LOGV) { HttpLog.v(errorMessage); } return new SslError(SslError.SSL_UNTRUSTED, currCertificate); } // verify if the dates are valid try { currCertificate.checkValidity(); } catch (CertificateExpiredException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "certificate expired"; } if (HttpLog.LOGV) { HttpLog.v(errorMessage); } if (error == null || error.getPrimaryError() < SslError.SSL_EXPIRED) { error = new SslError(SslError.SSL_EXPIRED, currCertificate); } } catch (CertificateNotYetValidException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "certificate not valid yet"; } if (HttpLog.LOGV) { HttpLog.v(errorMessage); } if (error == null || error.getPrimaryError() < SslError.SSL_NOTYETVALID) { error = new SslError(SslError.SSL_NOTYETVALID, currCertificate); } } prevCertificate = currCertificate; } // if we do not have an error to report back to the user, throw // an exception (a generic error will be reported instead) if (error == null) { closeSocketThrowException(sslSocket, "failed to pre-validate the certificate chain due to a non-standard error"); } return error; }
From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java
public UserDetails getUserFromCert(X509Certificate userCertificate) { String certDN = userCertificate.getSubjectDN().getName(); X500Name x500name = new X500Name(certDN); InetOrgPerson.Essence essence = new InetOrgPerson.Essence(); String name = getElement(x500name, BCStyle.CN); String uid = getElement(x500name, BCStyle.UID); essence.setUsername(uid);//from w ww .java2 s . co m essence.setUid(uid); essence.setDn(certDN); essence.setCn(new String[] { name }); essence.setSn(name); essence.setO(getElement(x500name, BCStyle.O)); essence.setOu(getElement(x500name, BCStyle.OU)); essence.setDescription(certDN); // Hack alert! There is no country property in this type, so we misuse PostalAddress... essence.setPostalAddress(getElement(x500name, BCStyle.C)); log.debug("Parsed certificate, name: " + name); // Extract info from Subject Alternative Name extension Collection<List<?>> san = null; try { san = userCertificate.getSubjectAlternativeNames(); } catch (CertificateParsingException e) { log.warn("could not extract info from Subject Alternative Names - will be ignored."); } // Check that the certificate includes the SubjectAltName extension if (san != null) { // Use the type OtherName to search for the certified server name Collection<GrantedAuthority> roles = new ArrayList<>(); for (List item : san) { Integer type = (Integer) item.get(0); if (type == 0) { // Type OtherName found so return the associated value ASN1InputStream decoder = null; String oid = ""; String value = ""; try { // Value is encoded using ASN.1 so decode it to get it out again decoder = new ASN1InputStream((byte[]) item.toArray()[1]); DLSequence seq = (DLSequence) decoder.readObject(); ASN1ObjectIdentifier asnOID = (ASN1ObjectIdentifier) seq.getObjectAt(0); ASN1Encodable encoded = seq.getObjectAt(1); encoded = ((DERTaggedObject) encoded).getObject(); encoded = ((DERTaggedObject) encoded).getObject(); oid = asnOID.getId(); value = ((DERUTF8String) encoded).getString(); } catch (UnsupportedEncodingException e) { log.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e); continue; } catch (Exception e) { log.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e); continue; } finally { if (decoder != null) { try { decoder.close(); } catch (IOException e) { } } } log.debug("oid: " + oid + ", value: " + value); switch (oid) { case MC_OID_FLAGSTATE: case MC_OID_CALLSIGN: case MC_OID_IMO_NUMBER: case MC_OID_MMSI_NUMBER: case MC_OID_AIS_SHIPTYPE: case MC_OID_PORT_OF_REGISTER: log.debug("Ship specific OIDs are ignored"); break; case MC_OID_MRN: // We only support 1 mrn essence.setUid(value); break; case MC_OID_PERMISSIONS: if (value != null && !value.trim().isEmpty()) { SimpleGrantedAuthority role = new SimpleGrantedAuthority(value); roles.add(role); } break; default: log.error("Unknown OID!"); break; } } else { // Other types are not supported so ignore them log.warn("SubjectAltName of invalid type found: " + type); } } if (!roles.isEmpty()) { essence.setAuthorities(roles); } } return essence.createUserDetails(); }
From source file:org.ejbca.core.protocol.ocsp.OCSPUnidExtension.java
/** Called by OCSP responder when the configured extension is found in the request. * /*from w ww . j ava2s. c o m*/ * @param request HttpServletRequest that can be used to find out information about caller, TLS certificate etc. * @param cert X509Certificate the caller asked for in the OCSP request * @param status CertificateStatus the status the certificate has according to the OCSP responder, null means the cert is good * @return X509Extension that will be added to responseExtensions by OCSP responder, or null if an error occurs */ public Hashtable process(HttpServletRequest request, X509Certificate cert, CertificateStatus status) { if (m_log.isTraceEnabled()) { m_log.trace(">process()"); } // Check authorization first if (!checkAuthorization(request)) { errCode = OCSPUnidExtension.ERROR_UNAUTHORIZED; return null; } // If the certificate is revoked, we must not return an FNR if (status != null) { errCode = OCSPUnidExtension.ERROR_CERT_REVOKED; return null; } Connection con = null; PreparedStatement ps = null; ResultSet result = null; String fnr = null; String sn = null; try { // The Unis is in the DN component serialNumber sn = CertTools.getPartFromDN(cert.getSubjectDN().getName(), "SN"); if (sn != null) { if (m_log.isDebugEnabled()) { m_log.debug("Found serialNumber: " + sn); } String iMsg = intres.getLocalizedMessage("ocsp.receivedunidreq", request.getRemoteAddr(), request.getRemoteHost(), sn); m_log.info(iMsg); try { con = ServiceLocator.getInstance().getDataSource(dataSourceJndi).getConnection(); } catch (SQLException e) { String errMsg = intres.getLocalizedMessage("ocsp.errordatabaseunid"); m_log.error(errMsg, e); errCode = OCSPUnidExtension.ERROR_SERVICE_UNAVAILABLE; return null; } ps = con.prepareStatement("select fnr from UnidFnrMapping where unid=?"); ps.setString(1, sn); result = ps.executeQuery(); if (result.next()) { fnr = result.getString(1); } } else { String errMsg = intres.getLocalizedMessage("ocsp.errorunidnosnindn", cert.getSubjectDN().getName()); m_log.error(errMsg); errCode = OCSPUnidExtension.ERROR_NO_SERIAL_IN_DN; return null; } m_log.trace("<process()"); } catch (Exception e) { throw new EJBException(e); } finally { JDBCUtil.close(con, ps, result); } // Construct the response extentsion if we found a mapping if (fnr == null) { String errMsg = intres.getLocalizedMessage("ocsp.errorunidnosnmapping", sn); m_log.error(errMsg); errCode = OCSPUnidExtension.ERROR_NO_FNR_MAPPING; return null; } String errMsg = intres.getLocalizedMessage("ocsp.returnedunidresponse", request.getRemoteAddr(), request.getRemoteHost(), fnr, sn); m_log.info(errMsg); FnrFromUnidExtension ext = new FnrFromUnidExtension(fnr); Hashtable ret = new Hashtable(); ret.put(FnrFromUnidExtension.FnrFromUnidOid, new X509Extension(false, new DEROctetString(ext))); return ret; }
From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java
private CertData fillCertData(X509Certificate cert, String alise, Format formatter) throws CertificateEncodingException { CertData certData = null;//from w w w . ja v a 2 s . c o m if (includeCert) { certData = new CertDataDetail(); } else { certData = new CertData(); } certData.setAlias(alise); certData.setSubjectDN(cert.getSubjectDN().getName()); certData.setIssuerDN(cert.getIssuerDN().getName()); certData.setSerialNumber(cert.getSerialNumber()); certData.setVersion(cert.getVersion()); certData.setNotAfter(formatter.format(cert.getNotAfter())); certData.setNotBefore(formatter.format(cert.getNotBefore())); certData.setPublicKey(Base64.encode(cert.getPublicKey().getEncoded())); if (includeCert) { ((CertDataDetail) certData).setCertificate(cert); } return certData; }
From source file:info.guardianproject.onionkit.trust.StrongTrustManager.java
private void showCertMessage(String title, String msg, X509Certificate cert, String fingerprint) { Intent nIntent = new Intent(mContext, CertDisplayActivity.class); nIntent.putExtra("issuer", cert.getIssuerDN().getName()); nIntent.putExtra("subject", cert.getSubjectDN().getName()); if (fingerprint != null) nIntent.putExtra("fingerprint", fingerprint); SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss", Locale.US); df.setTimeZone(TimeZone.getTimeZone("UTC")); nIntent.putExtra("issued", df.format(cert.getNotBefore()) + " GMT"); nIntent.putExtra("expires", df.format(cert.getNotAfter()) + " GMT"); nIntent.putExtra("msg", title + ": " + msg); showToolbarNotification(title, msg, DEFAULT_NOTIFY_ID, mAppIcon, Notification.FLAG_AUTO_CANCEL, nIntent); }