List of usage examples for java.security.cert X509Certificate getSubjectX500Principal
public X500Principal getSubjectX500Principal()
From source file:com.newrelic.agent.deps.org.apache.http.conn.ssl.SSLConnectionSocketFactory.java
private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException { try {//w ww.j a va2s . com 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 (this.log.isDebugEnabled()) { this.log.debug("Secure session established"); this.log.debug(" negotiated protocol: " + session.getProtocol()); this.log.debug(" negotiated cipher suite: " + session.getCipherSuite()); try { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal peer = x509.getSubjectX500Principal(); this.log.debug(" peer principal: " + peer.toString()); final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames(); if (altNames1 != null) { final List<String> altNames = new ArrayList<String>(); for (final List<?> aC : altNames1) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } this.log.debug(" peer alternative names: " + altNames); } final X500Principal issuer = x509.getIssuerX500Principal(); this.log.debug(" issuer principal: " + issuer.toString()); final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames(); if (altNames2 != null) { final List<String> altNames = new ArrayList<String>(); for (final List<?> aC : altNames2) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } this.log.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 (final IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (final Exception x) { /*ignore*/ } throw iox; } }
From source file:eu.peppol.outbound.transmission.As2MessageSender.java
private PeppolAs2SystemIdentifier getAs2SystemIdentifierForSender(X509Certificate ourCertificate) { PeppolAs2SystemIdentifier peppolAs2SystemIdentifier = null; try {// w w w .j ava2 s.c o m peppolAs2SystemIdentifier = PeppolAs2SystemIdentifier .valueOf(CommonName.valueOf(ourCertificate.getSubjectX500Principal())); } catch (InvalidAs2SystemIdentifierException e) { throw new IllegalStateException( "AS2 System Identifier could not be obtained from " + ourCertificate.getSubjectX500Principal(), e); } return peppolAs2SystemIdentifier; }
From source file:org.opensc.pkcs11.spi.PKCS11KeyStoreSpi.java
@Override public String engineGetCertificateAlias(Certificate certificate) { if (!(certificate instanceof X509Certificate)) { log.error("engineGetCertificateAlias: Only X.509 certificates are supported."); }/*from ww w . ja v a 2s . c o m*/ X509Certificate x509Certificate = (X509Certificate) certificate; X500Principal subject = x509Certificate.getSubjectX500Principal(); Map<String, PKCS11KSEntry> centries = getAllCertificatesForSubject(subject); for (String name : centries.keySet()) { try { PKCS11KSEntry entry = centries.get(name); if (entry.certificate != null && entry.getDecodedCertificate().equals(certificate)) return name; } catch (PKCS11Exception e) { log.error("PKCS11 Error decoding Certificate for entry " + name + ":", e); } catch (CertificateException e) { log.error("Certificate Error decoding Certificate for entry " + name + ":", e); } } return null; }
From source file:be.fedict.eid.applet.service.impl.handler.SignatureDataMessageHandler.java
public Object handleMessage(SignatureDataMessage message, Map<String, String> httpHeaders, HttpServletRequest request, HttpSession session) throws ServletException { LOG.debug("signature data message received"); byte[] signatureValue = message.signatureValue; List<X509Certificate> certificateChain = message.certificateChain; if (certificateChain.isEmpty()) { throw new ServletException("certificate chain is empty"); }//from www. j av a 2 s .co m X509Certificate signingCertificate = certificateChain.get(0); if (null == signingCertificate) { throw new ServletException("non-repudiation certificate missing"); } LOG.debug("non-repudiation signing certificate: " + signingCertificate.getSubjectX500Principal()); for (X509Certificate certificate : certificateChain) { LOG.debug("signing x509 cert: " + certificate.getSubjectX500Principal()); } PublicKey signingPublicKey = signingCertificate.getPublicKey(); /* * Verify the signature. */ String digestAlgo = SignatureDataMessageHandler.getDigestAlgo(session); byte[] expectedDigestValue = SignatureDataMessageHandler.getDigestValue(session); if (digestAlgo.endsWith("-PSS")) { LOG.debug("verifying RSA/PSS signature"); try { Signature signature = Signature.getInstance("RAWRSASSA-PSS", BouncyCastleProvider.PROVIDER_NAME); if ("SHA-256-PSS".equals(digestAlgo)) { LOG.debug("RSA/PSS SHA256"); signature.setParameter( new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1)); } signature.initVerify(signingPublicKey); signature.update(expectedDigestValue); boolean result = signature.verify(signatureValue); if (false == result) { throw new SecurityException("signature incorrect"); } } catch (Exception e) { LOG.debug("signature verification error: " + e.getMessage(), e); throw new ServletException("signature verification error: " + e.getMessage(), e); } } else { try { Signature signature = Signature.getInstance("RawRSA", BouncyCastleProvider.PROVIDER_NAME); signature.initVerify(signingPublicKey); ByteArrayOutputStream digestInfo = new ByteArrayOutputStream(); if ("SHA-1".equals(digestAlgo) || "SHA1".equals(digestAlgo)) { digestInfo.write(SHA1_DIGEST_INFO_PREFIX); } else if ("SHA-224".equals(digestAlgo)) { digestInfo.write(SHA224_DIGEST_INFO_PREFIX); } else if ("SHA-256".equals(digestAlgo)) { digestInfo.write(SHA256_DIGEST_INFO_PREFIX); } else if ("SHA-384".equals(digestAlgo)) { digestInfo.write(SHA384_DIGEST_INFO_PREFIX); } else if ("SHA-512".equals(digestAlgo)) { digestInfo.write(SHA512_DIGEST_INFO_PREFIX); } else if ("RIPEMD160".equals(digestAlgo)) { digestInfo.write(RIPEMD160_DIGEST_INFO_PREFIX); } else if ("RIPEMD128".equals(digestAlgo)) { digestInfo.write(RIPEMD128_DIGEST_INFO_PREFIX); } else if ("RIPEMD256".equals(digestAlgo)) { digestInfo.write(RIPEMD256_DIGEST_INFO_PREFIX); } digestInfo.write(expectedDigestValue); signature.update(digestInfo.toByteArray()); boolean result = signature.verify(signatureValue); if (false == result) { AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.signatureError(remoteAddress, signingCertificate); } throw new SecurityException("signature incorrect"); } } catch (Exception e) { LOG.debug("signature verification error: " + e.getMessage()); throw new ServletException("signature verification error: " + e.getMessage(), e); } } AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String userId = UserIdentifierUtil.getUserId(signingCertificate); auditService.signed(userId); } SignatureService signatureService = this.signatureServiceLocator.locateService(); try { signatureService.setHttpSessionObject(request.getSession()); signatureService.postSign(signatureValue, certificateChain); } catch (ExpiredCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED); } catch (RevokedCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED); } catch (TrustCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED); } catch (CertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE); } catch (Exception e) { /* * We don't want to depend on the full JavaEE profile in this * artifact. */ if ("javax.ejb.EJBException".equals(e.getClass().getName())) { Exception exception; try { Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException", new Class[] {}); exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {}); } catch (Exception e2) { LOG.debug("error: " + e.getMessage(), e); throw new SecurityException("error retrieving the root cause: " + e2.getMessage()); } if (exception instanceof ExpiredCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED); } if (exception instanceof RevokedCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED); } if (exception instanceof TrustCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED); } if (exception instanceof CertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE); } } throw new SecurityException("signature service error: " + e.getMessage(), e); } return new FinishedMessage(); }
From source file:org.nuxeo.ecm.platform.signature.core.sign.SignatureServiceImpl.java
protected boolean certificatePresentInPDF(Certificate userCert, List<X509Certificate> pdfCertificates) throws SignException { X509Certificate xUserCert = (X509Certificate) userCert; for (X509Certificate xcert : pdfCertificates) { // matching certificate found if (xcert.getSubjectX500Principal().equals(xUserCert.getSubjectX500Principal())) { return true; }//ww w . j a va 2 s.c o m } return false; }
From source file:test.unit.be.fedict.eid.applet.service.signer.OOXMLSignatureVerifierTest.java
@Test public void testSignedOOXML2() throws Exception { // setup//w w w . jav a 2 s .co m URL url = OOXMLSignatureVerifierTest.class.getResource("/signed.docx"); // operate OOXMLSignatureVerifier verifier = new OOXMLSignatureVerifier(); List<X509Certificate> result = verifier.getSigners(url); // verify assertNotNull(result); assertEquals(1, result.size()); X509Certificate signer = result.get(0); LOG.debug("signer: " + signer.getSubjectX500Principal()); byte[] document = IOUtils.toByteArray(url.openStream()); List<String> signatureResourceNames = verifier.getSignatureResourceNames(document); Document signatureDocument = verifier.getSignatureDocument(new ByteArrayInputStream(document), signatureResourceNames.get(0)); NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); Element signatureElement = (Element) signatureNodeList.item(0); KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement); domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE); OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(document); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); assertTrue(verifier.isValidOOXMLSignature(xmlSignature, document)); }
From source file:test.unit.be.fedict.eid.applet.service.signer.OOXMLSignatureVerifierTest.java
@Test public void testSignedOOXMLOffice2010ValidOOXML() throws Exception { // setup//from www .ja va 2 s . c o m URL url = OOXMLSignatureVerifierTest.class.getResource("/hallo.docx"); // operate OOXMLSignatureVerifier verifier = new OOXMLSignatureVerifier(); List<X509Certificate> result = verifier.getSigners(url); // verify assertNotNull(result); assertEquals(1, result.size()); X509Certificate signer = result.get(0); LOG.debug("signer: " + signer.getSubjectX500Principal()); byte[] document = IOUtils.toByteArray(url.openStream()); List<String> signatureResourceNames = verifier.getSignatureResourceNames(document); Document signatureDocument = verifier.getSignatureDocument(new ByteArrayInputStream(document), signatureResourceNames.get(0)); NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); Element signatureElement = (Element) signatureNodeList.item(0); KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement); domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE); OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(document); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); assertTrue(verifier.isValidOOXMLSignature(xmlSignature, document)); }
From source file:com.screenslicer.common.LenientHttpsConfig.java
private LenientHttpsConfig() { AsyncHttpClientConfig configTmp = null; SSLContext sslContextTmp = null; try {/* w w w .j ava 2 s.c om*/ AsyncHttpClient client = new AsyncHttpClient(); configTmp = client.getConfig(); IOUtils.closeQuietly(client); client = null; X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(CommonUtil.class.getResourceAsStream("screenslicer.internal.cert")); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); keyStore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert); KeyManagerFactory keyManager = KeyManagerFactory.getInstance("SunX509"); keyManager.init(keyStore, null); TrustManagerFactory trustManager = TrustManagerFactory.getInstance("X509"); trustManager.init(keyStore); sslContextTmp = SSLContext.getInstance("TLS"); sslContextTmp.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null); } catch (Throwable t) { } config = configTmp; sslContext = sslContextTmp; }
From source file:org.opensc.pkcs11.spi.PKCS11KeyStoreSpi.java
@Override public Certificate[] engineGetCertificateChain(String name) { Certificate endEntity = engineGetCertificate(name); if (endEntity == null) return null; if (!(endEntity instanceof X509Certificate)) { log.error("engineGetCertificateChain: Only X.509 certificates are supported."); return null; }// w w w. j a v a 2 s . c o m List<Certificate> ret = new ArrayList<Certificate>(); ret.add(endEntity); X509Certificate x509Certificate = (X509Certificate) endEntity; try { // OK ,this is acrude form of certificate chain evaluation. // Assuming, that the upper layer does a more detailed anlysis of the // validity period and key extensions, we only search the chain by // finding the issuing certificate on the token using the issuer DN // and trying to check the Signature on the certificate using the // public key on the next certificate. while (!isRootCA(x509Certificate)) { Map<String, PKCS11KSEntry> centries = getAllCertificatesForSubject( x509Certificate.getIssuerX500Principal()); X509Certificate x509NextCert = null; for (PKCS11KSEntry entry : centries.values()) { Certificate next = entry.getDecodedCertificate(); X509Certificate x509Next = (X509Certificate) next; if (!x509Next.getSubjectX500Principal().equals(x509Certificate.getIssuerX500Principal())) continue; try { x509Certificate.verify(x509Next.getPublicKey()); x509NextCert = x509Next; break; } catch (Exception e) { log.warn("Exception during evaluation of certificate chain:", e); } } if (x509NextCert == null) { //throw new CertificateException("Cannot find the issuing CA for certificate ["+x509Certificate+"]."); break; // to allow chains with one/leaf certificate only } x509Certificate = x509NextCert; ret.add(x509Certificate); } return ret.toArray(new Certificate[0]); } catch (Exception e) { log.error("Exception caught during analysis of the certificate chain:", e); } return null; }
From source file:be.fedict.trust.ocsp.OcspTrustLinker.java
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate, Date validationDate, RevocationData revocationData) { URI ocspUri = getOcspUri(childCertificate); if (null == ocspUri) { return null; }/*ww w .j a va2 s .c o m*/ LOG.debug("OCSP URI: " + ocspUri); OCSPResp ocspResp = this.ocspRepository.findOcspResponse(ocspUri, childCertificate, certificate); if (null == ocspResp) { LOG.debug("OCSP response not found"); return null; } int ocspRespStatus = ocspResp.getStatus(); if (OCSPResponseStatus.SUCCESSFUL != ocspRespStatus) { LOG.debug("OCSP response status: " + ocspRespStatus); return null; } Object responseObject; try { responseObject = ocspResp.getResponseObject(); } catch (OCSPException e) { LOG.debug("OCSP exception: " + e.getMessage(), e); return null; } BasicOCSPResp basicOCSPResp = (BasicOCSPResp) responseObject; try { X509Certificate[] responseCertificates = basicOCSPResp.getCerts(BouncyCastleProvider.PROVIDER_NAME); for (X509Certificate responseCertificate : responseCertificates) { LOG.debug("OCSP response cert: " + responseCertificate.getSubjectX500Principal()); LOG.debug("OCSP response cert issuer: " + responseCertificate.getIssuerX500Principal()); } TrustLinkerResult trustResult = TrustValidator .checkSignatureAlgorithm(basicOCSPResp.getSignatureAlgName()); if (!trustResult.isValid()) return trustResult; if (0 == responseCertificates.length) { /* * This means that the OCSP response has been signed by the * issuing CA itself. */ boolean verificationResult = basicOCSPResp.verify(certificate.getPublicKey(), BouncyCastleProvider.PROVIDER_NAME); if (false == verificationResult) { LOG.debug("OCSP response signature invalid"); return null; } } else { /* * We're dealing with a dedicated authorized OCSP Responder * certificate, or of course with a CA that issues the OCSP * Responses itself. */ X509Certificate ocspResponderCertificate = responseCertificates[0]; boolean verificationResult = basicOCSPResp.verify(ocspResponderCertificate.getPublicKey(), BouncyCastleProvider.PROVIDER_NAME); if (false == verificationResult) { LOG.debug("OCSP Responser response signature invalid"); return null; } if (false == Arrays.equals(certificate.getEncoded(), ocspResponderCertificate.getEncoded())) { // check certificate signature trustResult = TrustValidator.checkSignatureAlgorithm(ocspResponderCertificate.getSigAlgName()); if (!trustResult.isValid()) { return trustResult; } X509Certificate issuingCaCertificate; if (responseCertificates.length < 2) { LOG.debug("OCSP responder complete certificate chain missing"); /* * Here we assume that the OCSP Responder is directly * signed by the CA. */ issuingCaCertificate = certificate; } else { issuingCaCertificate = responseCertificates[1]; /* * Is next check really required? */ if (false == certificate.equals(issuingCaCertificate)) { LOG.debug("OCSP responder certificate not issued by CA"); return null; } } // check certificate signature trustResult = TrustValidator.checkSignatureAlgorithm(issuingCaCertificate.getSigAlgName()); if (!trustResult.isValid()) { return trustResult; } PublicKeyTrustLinker publicKeyTrustLinker = new PublicKeyTrustLinker(); trustResult = publicKeyTrustLinker.hasTrustLink(ocspResponderCertificate, issuingCaCertificate, validationDate, revocationData); if (null != trustResult) { if (!trustResult.isValid()) { LOG.debug("OCSP responder not trusted"); return null; } } if (null == ocspResponderCertificate .getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())) { LOG.debug("OCSP Responder certificate should have id-pkix-ocsp-nocheck"); /* * TODO: perform CRL validation on the OCSP Responder * certificate. On the other hand, do we really want to * check the checker? */ return null; } List<String> extendedKeyUsage; try { extendedKeyUsage = ocspResponderCertificate.getExtendedKeyUsage(); } catch (CertificateParsingException e) { LOG.debug("OCSP Responder parsing error: " + e.getMessage(), e); return null; } if (null == extendedKeyUsage) { LOG.debug("OCSP Responder certificate has no extended key usage extension"); return null; } if (false == extendedKeyUsage.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) { LOG.debug("OCSP Responder certificate should have a OCSPSigning extended key usage"); return null; } } else { LOG.debug("OCSP Responder certificate equals the CA certificate"); } } } catch (NoSuchProviderException e) { LOG.debug("JCA provider exception: " + e.getMessage(), e); return null; } catch (OCSPException e) { LOG.debug("OCSP exception: " + e.getMessage(), e); return null; } catch (CertificateEncodingException e) { LOG.debug("certificate encoding error: " + e.getMessage(), e); return null; } CertificateID certificateId; try { certificateId = new CertificateID(CertificateID.HASH_SHA1, certificate, childCertificate.getSerialNumber()); } catch (OCSPException e) { LOG.debug("OCSP exception: " + e.getMessage(), e); return null; } SingleResp[] singleResps = basicOCSPResp.getResponses(); for (SingleResp singleResp : singleResps) { CertificateID responseCertificateId = singleResp.getCertID(); if (false == certificateId.equals(responseCertificateId)) { continue; } Date thisUpdate = singleResp.getThisUpdate(); LOG.debug("OCSP thisUpdate: " + thisUpdate); LOG.debug("OCSP nextUpdate: " + singleResp.getNextUpdate()); long dt = Math.abs(thisUpdate.getTime() - validationDate.getTime()); if (dt > this.freshnessInterval) { LOG.warn("freshness interval exceeded: " + dt + " milliseconds"); continue; } if (null == singleResp.getCertStatus()) { LOG.debug("OCSP OK for: " + childCertificate.getSubjectX500Principal()); addRevocationData(revocationData, ocspResp); return new TrustLinkerResult(true); } else { LOG.debug("OCSP certificate status: " + singleResp.getCertStatus().getClass().getName()); if (singleResp.getCertStatus() instanceof RevokedStatus) { LOG.debug("OCSP status revoked"); } addRevocationData(revocationData, ocspResp); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_REVOCATION_STATUS, "certificate revoked by OCSP"); } } LOG.debug("no matching OCSP response entry"); return null; }