List of usage examples for java.security.cert CertStore getCertificates
public final Collection<? extends Certificate> getCertificates(CertSelector selector) throws CertStoreException
From source file:MainClass.java
public static void main(String args[]) throws Exception { CertificateFactory cf = CertificateFactory.getInstance("X.509"); List mylist = new ArrayList(); FileInputStream in = new FileInputStream(args[0]); Certificate c = cf.generateCertificate(in); mylist.add(c);/*from www . j ava2s.com*/ CertStoreParameters cparam = new CollectionCertStoreParameters(mylist); CertStore cs = CertStore.getInstance("Collection", cparam); X509CertSelector selec = new X509CertSelector(); selec.setIssuer("CN=YourName,OU=Network Center," + "O=University,L=ZB,ST=Toronto,C=CN"); Set clct = (Set) cs.getCertificates(selec); Object o[] = clct.toArray(); for (int i = 0; i < o.length; i++) { X509Certificate ct = (X509Certificate) o[i]; System.out.println("Certificate " + i + " "); System.out.println(ct.getSubjectDN()); } }
From source file:be.fedict.eid.dss.spi.utils.XAdESUtils.java
public static void verifyTimeStampTokenSignature(TimeStampToken timeStampToken) throws XAdESValidationException { try {//from w ww .ja v a 2 s.c om SignerId signerId = timeStampToken.getSID(); BigInteger signerCertSerialNumber = signerId.getSerialNumber(); //X500Principal signerCertIssuer = signerId.getIssuer(); X500Principal signerCertIssuer = new X500Principal(signerId.getIssuer().getEncoded()); CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection", BouncyCastleProvider.PROVIDER_NAME); Collection<? extends Certificate> certificates = certStore.getCertificates(null); X509Certificate tsaCertificate = null; for (Certificate certificate : certificates) { X509Certificate x509Certificate = (X509Certificate) certificate; if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal()) && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) { tsaCertificate = x509Certificate; break; } } if (null == tsaCertificate) { throw new XAdESValidationException("TSA certificate not present in TST"); } timeStampToken.validate(tsaCertificate, BouncyCastleProvider.PROVIDER_NAME); } catch (Exception e) { throw new XAdESValidationException(e); } }
From source file:be.fedict.eid.dss.model.bean.TrustValidationServiceBean.java
public void validate(TimeStampToken timeStampToken, List<OCSPResp> ocspResponses, List<X509CRL> crls) throws CertificateEncodingException, TrustDomainNotFoundException, RevocationDataNotFoundException, ValidationFailedException, NoSuchAlgorithmException, NoSuchProviderException, CMSException, CertStoreException, IOException { LOG.debug("performing historical TSA validation..."); String tsaTrustDomain = this.configuration.getValue(ConfigProperty.TSA_TRUST_DOMAIN, String.class); LOG.debug("TSA trust domain: " + tsaTrustDomain); Date validationDate = timeStampToken.getTimeStampInfo().getGenTime(); LOG.debug("TSA validation date is TST time: " + validationDate); LOG.debug("# TSA ocsp responses: " + ocspResponses.size()); LOG.debug("# TSA CRLs: " + crls.size()); /*/*ww w .jav a 2 s. c o m*/ *Building TSA chain. (Code from eID-applet) * */ SignerId signerId = timeStampToken.getSID(); BigInteger signerCertSerialNumber = signerId.getSerialNumber(); //X500Principal signerCertIssuer = signerId.getIssuer(); X500Principal signerCertIssuer = new X500Principal(signerId.getIssuer().getEncoded()); LOG.debug("signer cert serial number: " + signerCertSerialNumber); LOG.debug("signer cert issuer: " + signerCertIssuer); // TSP signer certificates retrieval CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection", BouncyCastleProvider.PROVIDER_NAME); Collection<? extends Certificate> certificates = certStore.getCertificates(null); X509Certificate signerCert = null; Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>(); for (Certificate certificate : certificates) { X509Certificate x509Certificate = (X509Certificate) certificate; if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal()) && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) { signerCert = x509Certificate; } String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate)); certificateMap.put(ski, x509Certificate); LOG.debug("embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski); } // TSP signer cert path building if (null == signerCert) { throw new RuntimeException("TSP response token has no signer certificate"); } List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>(); X509Certificate tsaIssuer = loadCertificate( "be/fedict/eid/dss/CA POLITICA SELLADO DE TIEMPO - COSTA RICA.crt"); X509Certificate rootCA = loadCertificate("be/fedict/eid/dss/CA RAIZ NACIONAL COSTA RICA.cer"); LOG.debug("adding to certificate chain: " + signerCert.getSubjectX500Principal()); tspCertificateChain.add(signerCert); LOG.debug("adding to certificate chain: " + tsaIssuer.getSubjectX500Principal()); tspCertificateChain.add(tsaIssuer); LOG.debug("adding to certificate chain: " + rootCA.getSubjectX500Principal()); tspCertificateChain.add(rootCA); /* * Perform PKI validation via eID Trust Service. */ getXkms2Client().validate(tsaTrustDomain, tspCertificateChain, validationDate, ocspResponses, crls); }
From source file:be.fedict.eid.applet.service.signer.time.TSPTimeStampService.java
public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception { // digest the message MessageDigest messageDigest = MessageDigest.getInstance(this.digestAlgo); byte[] digest = messageDigest.digest(data); // generate the TSP request BigInteger nonce = new BigInteger(128, new SecureRandom()); TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator(); requestGenerator.setCertReq(true);/* ww w. j a va 2s . co m*/ if (null != this.requestPolicy) { requestGenerator.setReqPolicy(this.requestPolicy); } TimeStampRequest request = requestGenerator.generate(this.digestAlgoOid, digest, nonce); byte[] encodedRequest = request.getEncoded(); // create the HTTP client HttpClient httpClient = new HttpClient(); if (null != this.username) { Credentials credentials = new UsernamePasswordCredentials(this.username, this.password); httpClient.getState().setCredentials(AuthScope.ANY, credentials); } if (null != this.proxyHost) { httpClient.getHostConfiguration().setProxy(this.proxyHost, this.proxyPort); } // create the HTTP POST request PostMethod postMethod = new PostMethod(this.tspServiceUrl); RequestEntity requestEntity = new ByteArrayRequestEntity(encodedRequest, "application/timestamp-query"); postMethod.addRequestHeader("User-Agent", this.userAgent); postMethod.setRequestEntity(requestEntity); // invoke TSP service int statusCode = httpClient.executeMethod(postMethod); if (HttpStatus.SC_OK != statusCode) { LOG.error("Error contacting TSP server " + this.tspServiceUrl); throw new Exception("Error contacting TSP server " + this.tspServiceUrl); } // HTTP input validation Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type"); if (null == responseContentTypeHeader) { throw new RuntimeException("missing Content-Type header"); } String contentType = responseContentTypeHeader.getValue(); if (!contentType.startsWith("application/timestamp-reply")) { LOG.debug("response content: " + postMethod.getResponseBodyAsString()); throw new RuntimeException("invalid Content-Type: " + contentType); } if (0 == postMethod.getResponseContentLength()) { throw new RuntimeException("Content-Length is zero"); } // TSP response parsing and validation InputStream inputStream = postMethod.getResponseBodyAsStream(); TimeStampResponse timeStampResponse = new TimeStampResponse(inputStream); timeStampResponse.validate(request); if (0 != timeStampResponse.getStatus()) { LOG.debug("status: " + timeStampResponse.getStatus()); LOG.debug("status string: " + timeStampResponse.getStatusString()); PKIFailureInfo failInfo = timeStampResponse.getFailInfo(); if (null != failInfo) { LOG.debug("fail info int value: " + failInfo.intValue()); if (PKIFailureInfo.unacceptedPolicy == failInfo.intValue()) { LOG.debug("unaccepted policy"); } } throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus()); } TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken(); SignerId signerId = timeStampToken.getSID(); BigInteger signerCertSerialNumber = signerId.getSerialNumber(); X500Principal signerCertIssuer = new X500Principal(signerId.getIssuer().getEncoded()); LOG.debug("signer cert serial number: " + signerCertSerialNumber); LOG.debug("signer cert issuer: " + signerCertIssuer); // TSP signer certificates retrieval CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection", BouncyCastleProvider.PROVIDER_NAME); Collection<? extends Certificate> certificates = certStore.getCertificates(null); X509Certificate signerCert = null; Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>(); for (Certificate certificate : certificates) { X509Certificate x509Certificate = (X509Certificate) certificate; if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal()) && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) { signerCert = x509Certificate; } String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate)); certificateMap.put(ski, x509Certificate); LOG.debug("embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski); } // TSP signer cert path building if (null == signerCert) { throw new RuntimeException("TSP response token has no signer certificate"); } List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>(); X509Certificate tsaIssuer = loadCertificate( "be/fedict/eid/applet/service/CA POLITICA SELLADO DE TIEMPO - COSTA RICA.crt"); X509Certificate rootCA = loadCertificate("be/fedict/eid/applet/service/CA RAIZ NACIONAL COSTA RICA.cer"); LOG.debug("adding to certificate chain: " + signerCert.getSubjectX500Principal()); tspCertificateChain.add(signerCert); LOG.debug("adding to certificate chain: " + tsaIssuer.getSubjectX500Principal()); tspCertificateChain.add(tsaIssuer); LOG.debug("adding to certificate chain: " + rootCA.getSubjectX500Principal()); tspCertificateChain.add(rootCA); // verify TSP signer signature timeStampToken.validate(tspCertificateChain.get(0), BouncyCastleProvider.PROVIDER_NAME); // verify TSP signer certificate this.validator.validate(tspCertificateChain, revocationData); LOG.debug("time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime()); byte[] timestamp = timeStampToken.getEncoded(); return timestamp; }
From source file:be.fedict.trust.service.bean.TrustServiceBean.java
@TransactionAttribute(TransactionAttributeType.REQUIRED) @SNMP(oid = SnmpConstants.VALIDATE_TSA)//from www . jav a 2 s . co m public ValidationResult validateTimestamp(String trustDomainName, byte[] encodedTimestampToken, boolean returnRevocationData) throws TSPException, IOException, CMSException, NoSuchAlgorithmException, NoSuchProviderException, CertStoreException, TrustDomainNotFoundException { LOG.debug("validate timestamp token"); /* * Parse embedded certificate chain */ List<X509Certificate> certificateChain = new LinkedList<X509Certificate>(); TimeStampToken timestampToken = new TimeStampToken(new CMSSignedData(encodedTimestampToken)); CertStore certStore = timestampToken.getCertificatesAndCRLs("Collection", "BC"); Collection<? extends Certificate> certificates = certStore.getCertificates(null); for (Certificate certificate : certificates) { certificateChain.add((X509Certificate) certificate); } if (TrustValidator.isSelfSigned(certificateChain.get(0))) { Collections.reverse(certificateChain); } /* * Validate */ TrustLinkerResult lastResult = null; RevocationData lastRevocationData = null; for (TrustDomainEntity trustDomain : getTrustDomains(trustDomainName)) { TrustValidator trustValidator = getTrustValidator(trustDomain, returnRevocationData); try { trustValidator.isTrusted(certificateChain); } catch (CertPathValidatorException ignored) { } if (trustValidator.getResult().isValid()) { LOG.debug("valid for trust domain: " + trustDomain.getName()); harvest(trustDomain, certificateChain); return new ValidationResult(trustValidator.getResult(), trustValidator.getRevocationData()); } lastResult = trustValidator.getResult(); lastRevocationData = trustValidator.getRevocationData(); } return new ValidationResult(lastResult, lastRevocationData); }
From source file:mitm.common.security.certpath.CertPathBuilderTest.java
@Test public void testBuildPathCRLUnavailableButCRLCheckOff() throws Exception { // add roots/* w ww . j a va 2 s . c o m*/ addCertificates("windows-xp-all-roots.p7b", rootStoreParams.getCertStore()); addCertificates("mitm-test-root.cer", rootStoreParams.getCertStore()); addCertificates("windows-xp-all-intermediates.p7b", certStoreParams.getCertStore()); addCertificates("mitm-test-ca.cer", certStoreParams.getCertStore()); addCertificates("testCertificates.p7b", certStoreParams.getCertStore()); trustAnchors = getTrustAnchors(); X509CertSelector selector = new X509CertSelector(); selector.setSerialNumber(BigIntegerUtils.hexDecode("115FD110A82F742D0AE14A71B651962")); selector.setIssuer("EMAILADDRESS=ca@example.com, CN=MITM Test CA, L=Amsterdam, ST=NH, C=NL"); CertificatePathBuilder builder = new PKIXCertificatePathBuilder(); builder.setTrustAnchors(trustAnchors); builder.addCertPathChecker(new SMIMEExtendedKeyUsageCertPathChecker()); builder.addCertStore(certStore); builder.setRevocationEnabled(false); CertPathBuilderResult result = builder.buildPath(selector); List<? extends Certificate> certificates = result.getCertPath().getCertificates(); assertEquals(2, certificates.size()); CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certificates)); Collection<? extends Certificate> foundCertificates = store.getCertificates(selector); assertEquals(1, foundCertificates.size()); }
From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java
/** * ? ? ? ?? ?_1 /*w w w. ja v a2s . c o m*/ * ? ? ? * * @param signers * @param clientCerts * @return * @throws CertStoreException */ private boolean checkNucOneCertificateType(SignerInformationStore signers, CertStore clientCerts) throws CertStoreException { Iterator it = signers.getSigners().iterator(); boolean result = false; while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); X509CertSelector signerConstraints = signer.getSID(); Collection certCollection = clientCerts.getCertificates(signerConstraints); Iterator certIt = certCollection.iterator(); if (certCollection.size() == 0) { throw new RuntimeException( " ? ? ."); } while (certIt.hasNext()) { X509Certificate userCert = (X509Certificate) certIt.next(); X509Certificate certForCheck = null; boolean isMyVersion = false; try { if (TypeOfRespondent.FIRM.equals(typeOfRespondent)) { X509Certificate certNuc1Gost = (X509Certificate) createCerificate_nuc1_gost(); userCert.verify(certNuc1Gost.getPublicKey(), providerName); certForCheck = certNuc1Gost; } else { X509Certificate certNuc1Rsa = (X509Certificate) createCerificate_nuc1_rsa(); userCert.verify(certNuc1Rsa.getPublicKey(), providerName); certForCheck = certNuc1Rsa; } isMyVersion = true; } catch (Exception ex) { // ? ? ? ? 1 result = false; } if (isMyVersion) { // ? ? ? ?? ?_1 try { certForCheck.checkValidity(); // ? ? ? } catch (CertificateExpiredException ex) { throw new RuntimeException( " ? ? ? 1.0, ? ? 1.0 ? ??"); } catch (CertificateNotYetValidException ex) { throw new RuntimeException( " ? ? ? 1.0, ? ? 1.0 ?."); } try { if (isNotRevokedCertNucOne(userCert)) { // ? ? ? return true; } else { throw new RuntimeException( "C ? ."); } } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); } } } } return result; }
From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java
/** * ? ? ? ?? ?_2 /*www . j a va2 s . c om*/ * ? ? ? * * @param signers * @param clientCerts * @return * @throws CertStoreException */ private boolean checkNucTwoCertificateType(SignerInformationStore signers, CertStore clientCerts) throws CertStoreException { Iterator it = signers.getSigners().iterator(); boolean result = false; while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); X509CertSelector signerConstraints = signer.getSID(); Collection certCollection = clientCerts.getCertificates(signerConstraints); Iterator certIt = certCollection.iterator(); //System.out.println( ); if (certCollection.size() == 0) { throw new RuntimeException( " ? ? ."); } while (certIt.hasNext()) { X509Certificate userCert = (X509Certificate) certIt.next(); boolean isMyVersion = false; X509Certificate certForCheck = null; try { if (TypeOfRespondent.FIRM.equals(typeOfRespondent)) { X509Certificate certNuc2Gost = (X509Certificate) createCerificate_nuc2_gost(); X509Certificate certKucGost = (X509Certificate) createCerificate_kuc_gost(); userCert.verify(certNuc2Gost.getPublicKey(), providerName); certNuc2Gost.verify(certKucGost.getPublicKey(), providerName); certForCheck = certNuc2Gost; } else { X509Certificate certNuc2Rsa = (X509Certificate) createCerificate_nuc2_rsa(); X509Certificate certKucRsa = (X509Certificate) createCerificate_kuc_rsa(); userCert.verify(certNuc2Rsa.getPublicKey(), providerName); certNuc2Rsa.verify(certKucRsa.getPublicKey(), providerName); certForCheck = certNuc2Rsa; } isMyVersion = true; } catch (Exception ex) { result = false; } if (isMyVersion) { // ? ? ? ?? ?_1 try { certForCheck.checkValidity(); } catch (CertificateExpiredException ex) { throw new RuntimeException( " ? ? ? 2.0, ? ? 2.0 ? ??"); } catch (CertificateNotYetValidException ex) { throw new RuntimeException( " ? ? ? 2.0, ? ? 2.0 ?."); } try { if (isNotRevokedCertNucTwo(userCert)) { result = true; return true; } else { throw new RuntimeException( "C ? ."); } } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); } } } } return result; }
From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java
/** * ? ? ? ? ?//from ww w.ja v a 2s . c om * * @param signers * @param clientCerts * @return */ private boolean reCheckClientSignature(SignerInformationStore signers, CertStore clientCerts) throws CertStoreException, NoSuchAlgorithmException, NoSuchProviderException, CMSException { Iterator it = signers.getSigners().iterator(); boolean overAllResult = true; while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); X509CertSelector signerConstraints = signer.getSID(); Collection certCollection = clientCerts.getCertificates(signerConstraints); Iterator certIt = certCollection.iterator(); int indexOfSigner = 0; while (certIt.hasNext()) { indexOfSigner++; X509Certificate cert = (X509Certificate) certIt.next(); //System.out.println( "------ ?: " + indexOfSigner+ " ----- "); //System.out.println( cert ); try { cert.checkValidity(); overAllResult = (overAllResult) && (signer.verify(cert, providerName)); } catch (CertificateExpiredException ex) { verifyErrorMsg = " ?? ? !"; Logger.getLogger(SecureManager.class.getName()).log(Level.SEVERE, "ORE SIGN2:", ex); return false; } catch (CertificateNotYetValidException ex) { verifyErrorMsg = " ? ?!"; Logger.getLogger(SecureManager.class.getName()).log(Level.SEVERE, "ORE SIGN3:", ex); return false; } } if (indexOfSigner == 0) { verifyErrorMsg = "? ? , ? ? ?!"; } if (!overAllResult) { verifyErrorMsg = " ? ? !"; } } return overAllResult; }
From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java
/** * ? ? ?? ?? '?'. /* w w w. ja v a 2s. c om*/ * @param signers * @param clientCerts * @return * @throws CertStoreException */ private boolean isBadKeyUsage(SignerInformationStore signers, CertStore clientCerts) throws CertStoreException { if (signers.getSigners().size() == 0) { verifyErrorMsg = " ?."; return true; } Iterator it = signers.getSigners().iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); X509CertSelector signerConstraints = signer.getSID(); Collection certCollection = clientCerts.getCertificates(signerConstraints); Iterator certIt = certCollection.iterator(); if (certCollection.size() == 0) { verifyErrorMsg = " ? ? ."; return true; } while (certIt.hasNext()) { X509Certificate cert = (X509Certificate) certIt.next(); if (cert.getKeyUsage()[0] && cert.getKeyUsage()[1]) { continue; } else { verifyErrorMsg = "? ?? ? ? c '??'."; return true; } } } return false; }