List of usage examples for java.security.cert X509Certificate getSubjectX500Principal
public X500Principal getSubjectX500Principal()
From source file:net.solarnetwork.node.setup.test.DefaultKeystoreServiceTest.java
@Test public void generatePKCS12Keystore() throws Exception { saveCASignedCert();/*from w w w . j a va 2 s. c om*/ reset(setupIdentityDao); SetupIdentityInfo info = new SetupIdentityInfo(1L, TEST_CONF_VALUE, "localhost", 80, false, TEST_PW_VALUE); expect(setupIdentityDao.getSetupIdentityInfo()).andReturn(info).atLeastOnce(); replay(setupIdentityDao); String keystoreData = service.generatePKCS12KeystoreString("foobar"); assertNotNull(keystoreData); byte[] data = Base64.decodeBase64(keystoreData); KeyStore keyStore = KeyStore.getInstance("pkcs12"); keyStore.load(new ByteArrayInputStream(data), "foobar".toCharArray()); Certificate cert = keyStore.getCertificate("node"); assertNotNull(cert); assertTrue(cert instanceof X509Certificate); X509Certificate nodeCert = (X509Certificate) cert; assertEquals(new X500Principal(TEST_DN), nodeCert.getSubjectX500Principal()); assertEquals(CA_CERT.getSubjectX500Principal(), nodeCert.getIssuerX500Principal()); }
From source file:mitm.common.security.crl.CRLLocator.java
public List<X509CRL> findCRLs(X509Certificate issuer) throws NoSuchProviderException { List<X509CRL> crls = new LinkedList<X509CRL>(); X509CRLSelector crlSelector = new X509CRLSelector(); crlSelector.addIssuer(issuer.getSubjectX500Principal()); /* //from w w w .j a v a 2 s .c o m * step through all the stores and get all the relevant CRLs from the stores */ for (BasicCRLStore store : crlStores) { try { CloseableIterator<? extends CRL> crlIterator = store.getCRLIterator(crlSelector); try { while (crlIterator.hasNext()) { CRL crl = crlIterator.next(); if (!(crl instanceof X509CRL)) { logger.warn("Only X509CRLs are supported. Skipping this CRL."); continue; } X509CRL x509CRL = (X509CRL) crl; if (acceptCRL(issuer, x509CRL)) { crls.add(x509CRL); } } } finally { crlIterator.close(); } } catch (CRLStoreException e) { /* * log and continue search * */ logger.error("Error getting CRLs. Skipping this store.", e); continue; } catch (CloseableIteratorException e) { /* * log and continue search */ logger.error("Error stepping through the CRL store. Skipping this store.", e); continue; } } return crls; }
From source file:be.fedict.trust.PublicKeyTrustLinker.java
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate, Date validationDate, RevocationData revocationData) { if (false == childCertificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal())) { LOG.debug("child certificate issuer not the same as the issuer certificate subject"); LOG.debug("child certificate: " + childCertificate.getSubjectX500Principal()); LOG.debug("certificate: " + certificate.getSubjectX500Principal()); LOG.debug("child certificate issuer: " + childCertificate.getIssuerX500Principal()); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "child certificate issuer not the same as the issuer certificate subject"); }// ww w.j av a2 s. co m try { childCertificate.verify(certificate.getPublicKey()); } catch (Exception e) { LOG.debug("verification error: " + e.getMessage(), e); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_SIGNATURE, "verification error: " + e.getMessage()); } if (true == childCertificate.getNotAfter().after(certificate.getNotAfter())) { LOG.warn("child certificate validity end is after certificate validity end"); LOG.warn("child certificate validity end: " + childCertificate.getNotAfter()); LOG.warn("certificate validity end: " + certificate.getNotAfter()); } if (true == childCertificate.getNotBefore().before(certificate.getNotBefore())) { LOG.warn("child certificate validity begin before certificate validity begin"); LOG.warn("child certificate validity begin: " + childCertificate.getNotBefore()); LOG.warn("certificate validity begin: " + certificate.getNotBefore()); } if (true == validationDate.before(childCertificate.getNotBefore())) { LOG.debug("certificate is not yet valid"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL, "certificate is not yet valid"); } if (true == validationDate.after(childCertificate.getNotAfter())) { LOG.debug("certificate already expired"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL, "certificate already expired"); } if (-1 == certificate.getBasicConstraints()) { LOG.debug("certificate not a CA"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "certificate not a CA"); } if (0 == certificate.getBasicConstraints() && -1 != childCertificate.getBasicConstraints()) { LOG.debug("child should not be a CA"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "child should not be a CA"); } /* * SKID/AKID sanity check */ boolean isCa = isCa(certificate); boolean isChildCa = isCa(childCertificate); byte[] subjectKeyIdentifierData = certificate .getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId()); byte[] authorityKeyIdentifierData = childCertificate .getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId()); if (isCa && null == subjectKeyIdentifierData) { LOG.debug("certificate is CA and MUST contain a Subject Key Identifier"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "certificate is CA and MUST contain a Subject Key Identifier"); } if (isChildCa && null == authorityKeyIdentifierData) { LOG.debug("child certificate is CA and MUST contain an Authority Key Identifier"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "child certificate is CA and MUST contain an Authority Key Identifier"); } if (null != subjectKeyIdentifierData && null != authorityKeyIdentifierData) { AuthorityKeyIdentifierStructure authorityKeyIdentifierStructure; try { authorityKeyIdentifierStructure = new AuthorityKeyIdentifierStructure(authorityKeyIdentifierData); } catch (IOException e) { LOG.debug("Error parsing authority key identifier structure"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "Error parsing authority key identifier structure"); } String akidId = new String(Hex.encodeHex(authorityKeyIdentifierStructure.getKeyIdentifier())); SubjectKeyIdentifierStructure subjectKeyIdentifierStructure; try { subjectKeyIdentifierStructure = new SubjectKeyIdentifierStructure(subjectKeyIdentifierData); } catch (IOException e) { LOG.debug("Error parsing subject key identifier structure"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "Error parsing subject key identifier structure"); } String skidId = new String(Hex.encodeHex(subjectKeyIdentifierStructure.getKeyIdentifier())); if (!skidId.equals(akidId)) { LOG.debug( "certificate's subject key identifier does not match child certificate's authority key identifier"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "certificate's subject key identifier does not match child certificate's authority key identifier"); } } /* * We don't check pathLenConstraint since this one is only there to * protect the PKI business. */ return null; }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
public static PKCS10CertificationRequest generateCertificateRequest(X509Certificate cert, PrivateKey signingKey) throws Exception { ASN1EncodableVector attributes = new ASN1EncodableVector(); Set<String> nonCriticalExtensionOIDs = cert.getNonCriticalExtensionOIDs(); for (String nceoid : nonCriticalExtensionOIDs) { byte[] derBytes = cert.getExtensionValue(nceoid); ByteArrayInputStream bis = new ByteArrayInputStream(derBytes); ASN1InputStream dis = new ASN1InputStream(bis); try {/* w w w .jav a 2 s . c o m*/ DERObject derObject = dis.readObject(); DERSet value = new DERSet(derObject); Attribute attr = new Attribute(new DERObjectIdentifier(nceoid), value); attributes.add(attr); } finally { IOUtils.closeQuietly(dis); } } PKCS10CertificationRequest certificationRequest = new PKCS10CertificationRequest(getSignatureAlgorithm(), cert.getSubjectX500Principal(), cert.getPublicKey(), new DERSet(attributes), signingKey); return certificationRequest; }
From source file:com.vmware.identity.idm.server.clientcert.IdmClientCertificateValidator.java
/** * * @return keyStore representing that containing the trust CA certificates of the tenant * @throws InvalidArgumentException/*from w ww . j ava2s.c o m*/ */ private KeyStore getTrustedClientCaStore() throws InvalidArgumentException { KeyStore trustedClientCaStore; if (certPolicy == null || certPolicy.getTrustedCAs() == null) { throw new InvalidArgumentException("Null client certificate policy or trust ca certficagtes."); } try { trustedClientCaStore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e1) { throw new InvalidArgumentException("Failed in creating a keyStore instance: ", e1); } try { trustedClientCaStore.load(null, null); } catch (NoSuchAlgorithmException | CertificateException | IOException e1) { throw new InvalidArgumentException("Failed in initializing a keyStore instance: " + e1.getMessage(), e1); } for (Certificate trustCa : certPolicy.getTrustedCAs()) { X509Certificate x509Cert = (X509Certificate) trustCa; try { trustedClientCaStore.setCertificateEntry(x509Cert.getSubjectX500Principal().getName(), trustCa); } catch (KeyStoreException e) { throw new InvalidArgumentException("Failed in storing a ca cert to keyStore: " + e.getMessage(), e); } } return trustedClientCaStore; }
From source file:be.fedict.eid.dss.protocol.simple.client.SignatureResponseProcessor.java
private void verifyServiceSignature(String serviceSigned, String target, String signatureRequest, String signatureRequestId, String signatureResponse, String signatureResponseId, String encodedSignatureCertificate, byte[] serviceSignatureValue, List<X509Certificate> serviceCertificateChain) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { LOG.debug("verifying service signature"); X509Certificate serviceCertificate = serviceCertificateChain.get(0); LOG.debug("service identity: " + serviceCertificate.getSubjectX500Principal()); Signature serviceSignature = Signature.getInstance("SHA1withRSA"); serviceSignature.initVerify(serviceCertificate); StringTokenizer serviceSignedStringTokenizer = new StringTokenizer(serviceSigned, ","); while (serviceSignedStringTokenizer.hasMoreTokens()) { String serviceSignedElement = serviceSignedStringTokenizer.nextToken(); LOG.debug("service signed: " + serviceSignedElement); byte[] data; if ("target".equals(serviceSignedElement)) { data = target.getBytes();/*from w w w . j ava 2 s . co m*/ } else if ("SignatureRequest".equals(serviceSignedElement)) { data = signatureRequest.getBytes(); } else if ("SignatureRequestId".equals(serviceSignedElement)) { data = signatureRequestId.getBytes(); } else if ("SignatureResponse".equals(serviceSignedElement)) { data = signatureResponse.getBytes(); } else if ("SignatureResponseId".equals(serviceSignedElement)) { data = signatureResponseId.getBytes(); } else if ("SignatureCertificate".equals(serviceSignedElement)) { data = encodedSignatureCertificate.getBytes(); } else { throw new SecurityException("service signed unknown element: " + serviceSignedElement); } serviceSignature.update(data); } boolean valid = serviceSignature.verify(serviceSignatureValue); if (!valid) { throw new SecurityException("service signature not valid"); } if (null != this.serviceFingerprint) { LOG.debug("checking service fingerprint"); byte[] actualServiceFingerprint = DigestUtils.sha(serviceCertificate.getEncoded()); if (!Arrays.equals(this.serviceFingerprint, actualServiceFingerprint)) { throw new SecurityException("service certificate fingerprint mismatch"); } } }
From source file:net.solarnetwork.node.setup.test.DefaultSetupServiceTest.java
@Test public void renewNetworkCertificate() throws Exception { SetupIdentityInfo info = new SetupIdentityInfo(1L, TEST_CONF_VALUE, TEST_SOLARIN_HOST, getHttpServerPort(), false, TEST_PW_VALUE);//w ww . j ava 2 s .c o m expect(setupIdentityDao.getSetupIdentityInfo()).andReturn(info).atLeastOnce(); replayAll(); keystoreService.saveCACertificate(CA_CERT); keystoreService.generateNodeSelfSignedCertificate(TEST_DN); String csr = keystoreService.generateNodePKCS10CertificateRequestString(); X509Certificate originalCert; PemReader pemReader = new PemReader(new StringReader(csr)); try { PemObject pem = pemReader.readPemObject(); PKCS10CertificationRequest req = new PKCS10CertificationRequest(pem.getContent()); originalCert = PKITestUtils.sign(req, CA_CERT, CA_KEY_PAIR.getPrivate()); String signedPem = PKITestUtils.getPKCS7Encoding(new X509Certificate[] { originalCert }); keystoreService.saveNodeSignedCertificate(signedPem); log.debug("Saved signed node certificate {}:\n{}", originalCert.getSerialNumber(), signedPem); assertThat("Generated CSR", csr, notNullValue()); } finally { pemReader.close(); } // now let's renew! AbstractTestHandler handler = new AbstractTestHandler() { @Override protected boolean handleInternal(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws Exception { assertEquals("POST", request.getMethod()); assertEquals("/solarin/api/v1/sec/cert/renew", target); String password = request.getParameter("password"); assertEquals("foobar", password); String keystoreData = request.getParameter("keystore"); assertNotNull(keystoreData); byte[] data = Base64.decodeBase64(keystoreData); KeyStore keyStore = KeyStore.getInstance("pkcs12"); keyStore.load(new ByteArrayInputStream(data), password.toCharArray()); Certificate cert = keyStore.getCertificate("node"); assertNotNull(cert); assertTrue(cert instanceof X509Certificate); X509Certificate nodeCert = (X509Certificate) cert; assertEquals(new X500Principal(TEST_DN), nodeCert.getSubjectX500Principal()); assertEquals(CA_CERT.getSubjectX500Principal(), nodeCert.getIssuerX500Principal()); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.write("{\"success\":true}"); out.flush(); response.flushBuffer(); return true; } }; httpServer.addHandler(handler); service.renewNetworkCertificate("foobar"); }
From source file:org.apache.http.HC4.conn.ssl.AbstractVerifier.java
public static String[] getCNs(X509Certificate cert) { LinkedList<String> cnList = new LinkedList<String>(); /*/* w w w .ja v a 2s. c o m*/ Sebastian Hauer's original StrictSSLProtocolSocketFactory used getName() and had the following comment: Parses a X.500 distinguished name for the value of the "Common Name" field. This is done a bit sloppy right now and should probably be done a bit more according to <code>RFC 2253</code>. I've noticed that toString() seems to do a better job than getName() on these X500Principal objects, so I'm hoping that addresses Sebastian's concern. For example, getName() gives me this: 1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d whereas toString() gives me this: EMAILADDRESS=juliusdavies@cucbc.com Looks like toString() even works with non-ascii domain names! I tested it with "花子.co.jp" and it worked fine. */ String subjectPrincipal = cert.getSubjectX500Principal().toString(); StringTokenizer st = new StringTokenizer(subjectPrincipal, ","); while (st.hasMoreTokens()) { String tok = st.nextToken(); int x = tok.indexOf("CN="); if (x >= 0) { cnList.add(tok.substring(x + 3)); } } if (!cnList.isEmpty()) { String[] cns = new String[cnList.size()]; cnList.toArray(cns); return cns; } else { return null; } }
From source file:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java
private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException { try {/* w ww. ja v a 2 s . c om*/ SSLSession session = sslsock.getSession(); if (session == null) { // In our experience this only happens under IBM 1.4.x when // spurious (unrelated) certificates show up in the server' // chain. Hopefully this will unearth the real problem: final InputStream in = sslsock.getInputStream(); in.available(); // If ssl.getInputStream().available() didn't cause an // exception, maybe at least now the session is available? session = sslsock.getSession(); if (session == null) { // If it's still null, probably a startHandshake() will // unearth the real problem. sslsock.startHandshake(); session = sslsock.getSession(); } } if (session == null) { throw new SSLHandshakeException("SSL session not available"); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Secure session established"); LOGGER.debug(" negotiated protocol: {}", session.getProtocol()); LOGGER.debug(" negotiated cipher suite: {}", session.getCipherSuite()); try { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal peer = x509.getSubjectX500Principal(); LOGGER.debug(" peer principal: {}", peer); final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames(); if (altNames1 != null) { final List<String> altNames = new ArrayList<>(); for (final List<?> aC : altNames1) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } LOGGER.debug(" peer alternative names: {}", altNames); } final X500Principal issuer = x509.getIssuerX500Principal(); LOGGER.debug(" issuer principal: {}", issuer); final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames(); if (altNames2 != null) { final List<String> altNames = new ArrayList<>(); for (final List<?> aC : altNames2) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } LOGGER.debug(" issuer alternative names: {}", altNames); } } catch (Exception ignore) { } } if (!this.hostnameVerifier.verify(hostname, session)) { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal x500Principal = x509.getSubjectX500Principal(); throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match " + "the certificate subject provided by the peer (" + x500Principal.toString() + ")"); } // verifyHostName() didn't blowup - good! } catch (RuntimeException | IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (final Exception x) { iox.addSuppressed(x); } throw iox; } }
From source file:be.e_contract.mycarenet.etee.EncryptionToken.java
private X509Certificate parseEncryptionCertificate(byte[] encodedEncryptionToken) throws CMSException, CertificateException, IOException, OperatorCreationException { CMSSignedData cmsSignedData = new CMSSignedData(encodedEncryptionToken); // get signer identifier SignerInformationStore signers = cmsSignedData.getSignerInfos(); SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next(); SignerId signerId = signer.getSID(); // get signer certificate Store certificateStore = cmsSignedData.getCertificates(); LOG.debug("certificate store type: " + certificateStore.getClass().getName()); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> signingCertificateCollection = certificateStore.getMatches(signerId); X509CertificateHolder signingCertificateHolder = signingCertificateCollection.iterator().next(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate signingCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(signingCertificateHolder.getEncoded())); LOG.debug("signing certificate: " + signingCertificate.getSubjectX500Principal()); // verify CMS signature SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder() .build(signingCertificate);//from w ww. j av a 2 s. c o m boolean signatureResult = signer.verify(signerInformationVerifier); if (false == signatureResult) { throw new SecurityException("ETK signature invalid"); } // get encryption certificate CMSTypedData signedContent = cmsSignedData.getSignedContent(); byte[] data = (byte[]) signedContent.getContent(); X509Certificate encryptionCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(data)); LOG.debug("all available certificates:"); logCertificates(certificateStore, null); // get authentication certificate CustomSelector authenticationSelector = new CustomSelector(); authenticationSelector.setSubject(encryptionCertificate.getIssuerX500Principal()); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> authenticationCertificates = certificateStore .getMatches(authenticationSelector); if (authenticationCertificates.size() != 1) { LOG.debug("no authentication certificate match"); } X509CertificateHolder authenticationCertificateHolder = authenticationCertificates.iterator().next(); this.authenticationCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(authenticationCertificateHolder.getEncoded())); verifyProxyCertificate(encryptionCertificate, this.authenticationCertificate); return encryptionCertificate; }