List of usage examples for org.bouncycastle.tsp TimeStampToken getTimeStampInfo
public TimeStampTokenInfo getTimeStampInfo()
From source file:be.apsu.extremon.probes.tsp.TSPProbe.java
License:Open Source License
public void probe_forever() { double start = 0, end = 0; BigInteger requestNonce;//from w ww . j a v a2 s.co m byte[] requestHashedMessage = new byte[20]; List<String> comments = new ArrayList<String>(); STATE result = STATE.OK; log("running"); this.running = true; while (this.running) { comments.clear(); this.random.nextBytes(requestHashedMessage); requestNonce = new BigInteger(512, this.random); TimeStampRequest request = requestGenerator.generate(TSPAlgorithms.SHA1, requestHashedMessage, requestNonce); end = 0; start = System.currentTimeMillis(); try { TimeStampResponse response = probe(request); switch (response.getStatus()) { case PKIStatus.GRANTED: comments.add("granted"); result = STATE.OK; break; case PKIStatus.GRANTED_WITH_MODS: comments.add("granted with modifications"); result = STATE.WARNING; break; case PKIStatus.REJECTION: comments.add("rejected"); result = STATE.ALERT; break; case PKIStatus.WAITING: comments.add("waiting"); result = STATE.ALERT; break; case PKIStatus.REVOCATION_WARNING: comments.add("revocation warning"); result = STATE.WARNING; break; case PKIStatus.REVOCATION_NOTIFICATION: comments.add("revocation notification"); result = STATE.ALERT; break; default: comments.add("response outside RFC3161"); result = STATE.ALERT; break; } if (response.getStatus() >= 2) comments.add(response.getFailInfo() != null ? response.getFailInfo().getString() : "(missing failinfo)"); if (response.getStatusString() != null) comments.add(response.getStatusString()); end = System.currentTimeMillis(); TimeStampToken timestampToken = response.getTimeStampToken(); timestampToken.validate(this.signerVerifier); comments.add("validated"); AttributeTable table = timestampToken.getSignedAttributes(); TimeStampTokenInfo tokenInfo = timestampToken.getTimeStampInfo(); BigInteger responseNonce = tokenInfo.getNonce(); byte[] responseHashedMessage = tokenInfo.getMessageImprintDigest(); long genTimeSeconds = (tokenInfo.getGenTime().getTime()) / 1000; long currentTimeSeconds = (long) (start + ((end - start) / 2)) / 1000; put("clockskew", (genTimeSeconds - currentTimeSeconds) * 1000); if (Math.abs((genTimeSeconds - currentTimeSeconds)) > 1) { comments.add("clock skew > 1s"); result = STATE.ALERT; } Store responseCertificatesStore = timestampToken.toCMSSignedData().getCertificates(); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> certs = responseCertificatesStore.getMatches(null); for (X509CertificateHolder certificate : certs) { AlgorithmIdentifier sigalg = certificate.getSignatureAlgorithm(); if (!(oidsAllowed.contains(sigalg.getAlgorithm().getId()))) { String cleanDn = certificate.getSubject().toString().replace("=", ":"); comments.add("signature cert \"" + cleanDn + "\" signed using " + getName(sigalg.getAlgorithm().getId())); result = STATE.ALERT; } } if (!responseNonce.equals(requestNonce)) { comments.add("nonce modified"); result = STATE.ALERT; } if (!Arrays.equals(responseHashedMessage, requestHashedMessage)) { comments.add("hashed message modified"); result = STATE.ALERT; } if (table.get(PKCSObjectIdentifiers.id_aa_signingCertificate) == null) { comments.add("signingcertificate missing"); result = STATE.ALERT; } } catch (TSPException tspEx) { comments.add("validation failed"); comments.add("tspexception-" + tspEx.getMessage().toLowerCase()); result = STATE.ALERT; } catch (IOException iox) { comments.add("unable to obtain response"); comments.add("ioexception-" + iox.getMessage().toLowerCase()); result = STATE.ALERT; } catch (Exception ex) { comments.add("unhandled exception"); result = STATE.ALERT; } finally { if (end == 0) end = System.currentTimeMillis(); } put(RESULT_SUFFIX, result); put(RESULT_COMMENT_SUFFIX, StringUtils.join(comments, "|")); put("responsetime", (end - start)); try { Thread.sleep(this.delay); } catch (InterruptedException ex) { log("interrupted"); } } }
From source file:be.fedict.eid.applet.service.signer.time.TSPTimeStampService.java
License:Open Source License
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);//from w w w . j ava2 s. c o 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 = signerId.getIssuer(); 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 certificate = signerCert; do { LOG.debug("adding to certificate chain: " + certificate.getSubjectX500Principal()); tspCertificateChain.add(certificate); if (certificate.getSubjectX500Principal().equals(certificate.getIssuerX500Principal())) { break; } String aki = Hex.encodeHexString(getAuthorityKeyId(certificate)); certificate = certificateMap.get(aki); } while (null != certificate); // 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.eid.dss.model.bean.TrustValidationServiceBean.java
License:Open Source License
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()); /*//from ww w . ja va2 s . com *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.dss.spi.utils.XAdESUtils.java
License:Open Source License
public static void verifyTimeStampTokenDigest(TimeStampToken timeStampToken, TimeStampDigestInput digestInput) throws XAdESValidationException { LOG.debug("digest verification: algo=" + timeStampToken.getTimeStampInfo().getMessageImprintAlgOID()); MessageDigest md;/*from ww w . j a v a 2 s . com*/ try { md = MessageDigest.getInstance(timeStampToken.getTimeStampInfo().getMessageImprintAlgOID().getId()); } catch (NoSuchAlgorithmException e) { throw new XAdESValidationException(e); } // LOG.debug("digest input: " + new String(digestInput.getBytes())); if (!Arrays.equals(md.digest(digestInput.getBytes()), timeStampToken.getTimeStampInfo().getMessageImprintDigest())) { throw new XAdESValidationException("Digest verification failure for " + "timestamp token"); } }
From source file:be.fedict.eid.dss.spi.utils.XAdESValidation.java
License:Open Source License
public SignatureInfo validate(Document document, XMLSignature xmlSignature, Element signatureElement, X509Certificate signingCertificate) throws XAdESValidationException { try {//from w w w . ja v a 2 s . co m /* * Get signing time from XAdES-BES extension. */ Element nsElement = getNsElement(document); Element qualifyingPropertiesElement = XAdESUtils.findQualifyingPropertiesElement(nsElement, xmlSignature, signatureElement); if (null == qualifyingPropertiesElement) { throw new XAdESValidationException("no matching xades:QualifyingProperties present"); } QualifyingPropertiesType qualifyingProperties = XAdESUtils.unmarshall(qualifyingPropertiesElement, QualifyingPropertiesType.class); if (false == qualifyingProperties.getTarget().equals("#" + xmlSignature.getId())) { throw new XAdESValidationException("xades:QualifyingProperties/@Target incorrect"); } SignedPropertiesType signedProperties = qualifyingProperties.getSignedProperties(); SignedSignaturePropertiesType signedSignatureProperties = signedProperties .getSignedSignatureProperties(); XMLGregorianCalendar signingTimeXMLGregorianCalendar = signedSignatureProperties.getSigningTime(); DateTime signingTime = new DateTime(signingTimeXMLGregorianCalendar.toGregorianCalendar().getTime()); LOG.debug("XAdES signing time: " + signingTime); /* * Check the XAdES signing certificate */ XAdESUtils.checkSigningCertificate(signingCertificate, signedSignatureProperties); /* * Get XAdES ClaimedRole. */ String role = null; SignerRoleType signerRole = signedSignatureProperties.getSignerRole(); if (null != signerRole) { ClaimedRolesListType claimedRolesList = signerRole.getClaimedRoles(); if (null != claimedRolesList) { List<AnyType> claimedRoles = claimedRolesList.getClaimedRole(); if (!claimedRoles.isEmpty()) { AnyType claimedRole = claimedRoles.get(0); List<Object> claimedRoleContent = claimedRole.getContent(); for (Object claimedRoleContentItem : claimedRoleContent) { if (claimedRoleContentItem instanceof String) { role = (String) claimedRoleContentItem; LOG.debug("XAdES claimed role: " + role); break; } } } } } // XAdES-T // validate first SignatureTimeStamp Element signatureTimeStampElement = XAdESUtils .findUnsignedSignaturePropertyElement(qualifyingPropertiesElement, "SignatureTimeStamp"); if (null == signatureTimeStampElement) { throw new XAdESValidationException("no xades:SignatureTimeStamp present"); } XAdESTimeStampType signatureTimeStamp = XAdESUtils.unmarshall(signatureTimeStampElement, XAdESTimeStampType.class); List<TimeStampToken> signatureTimeStampTokens = XAdESSignatureTimeStampValidation .verify(signatureTimeStamp, signatureElement); // XAdES-X // validate first SigAndRefsTimeStamp Element sigAndRefsTimeStampElement = XAdESUtils .findUnsignedSignaturePropertyElement(qualifyingPropertiesElement, "SigAndRefsTimeStamp"); if (null == sigAndRefsTimeStampElement) { LOG.error("No SigAndRefsTimeStamp present"); throw new XAdESValidationException("no xades:SigAndRefsTimeStamp present"); } XAdESTimeStampType sigAndRefsTimeStamp = XAdESUtils.unmarshall(sigAndRefsTimeStampElement, XAdESTimeStampType.class); List<TimeStampToken> sigAndRefsTimeStampTokens = XAdESSigAndRefsTimeStampValidation .verify(sigAndRefsTimeStamp, signatureElement); // timestamp tokens trust validation LOG.debug("validate SignatureTimeStamp's trust..."); ValidationDataType signatureTimeStampValidationData = XAdESUtils.findNextSibling( signatureTimeStampElement, XAdESUtils.XADES_141_NS_URI, "TimeStampValidationData", ValidationDataType.class); if (null != signatureTimeStampValidationData) { LOG.debug("xadesv141:TimeStampValidationData present for xades:SignatureTimeStamp"); RevocationValuesType revocationValues = signatureTimeStampValidationData.getRevocationValues(); List<X509CRL> crls = XAdESUtils.getCrls(revocationValues); List<OCSPResp> ocspResponses = XAdESUtils.getOCSPResponses(revocationValues); for (TimeStampToken signatureTimeStampToken : signatureTimeStampTokens) { this.documentContext.validate(signatureTimeStampToken, ocspResponses, crls); } } else { for (TimeStampToken signatureTimeStampToken : signatureTimeStampTokens) { this.documentContext.validate(signatureTimeStampToken); } } LOG.debug("validate SigAndRefsTimeStamp's trust..."); ValidationDataType sigAndRefsTimeStampValidationData = XAdESUtils.findNextSibling( sigAndRefsTimeStampElement, XAdESUtils.XADES_141_NS_URI, "TimeStampValidationData", ValidationDataType.class); if (null != sigAndRefsTimeStampValidationData) { LOG.debug("xadesv141:TimeStampValidationData present for xades:SigAndRefsTimeStamp"); RevocationValuesType revocationValues = sigAndRefsTimeStampValidationData.getRevocationValues(); List<X509CRL> crls = XAdESUtils.getCrls(revocationValues); List<OCSPResp> ocspResponses = XAdESUtils.getOCSPResponses(revocationValues); for (TimeStampToken sigAndRefsTimeStampToken : sigAndRefsTimeStampTokens) { this.documentContext.validate(sigAndRefsTimeStampToken, ocspResponses, crls); } } else { for (TimeStampToken sigAndRefsTimeStampToken : sigAndRefsTimeStampTokens) { this.documentContext.validate(sigAndRefsTimeStampToken); } } // timestamp tokens time coherence verification long timestampMaxOffset = this.documentContext.getTimestampMaxOffset(); LOG.debug("validate timestamp tokens time coherence..."); for (TimeStampToken signatureTimeStampToken : signatureTimeStampTokens) { DateTime stsTokenGenTime = new DateTime(signatureTimeStampToken.getTimeStampInfo().getGenTime()); try { XAdESUtils.checkCloseEnough(signingTime, stsTokenGenTime, timestampMaxOffset); } catch (XAdESValidationException e) { throw new XAdESValidationException("SignatureTimeStamp too far from SigningTime", e); } for (TimeStampToken sigAndRefsTimeStampToken : sigAndRefsTimeStampTokens) { DateTime sigAndRefsTokenGenTime = new DateTime( sigAndRefsTimeStampToken.getTimeStampInfo().getGenTime()); if (sigAndRefsTokenGenTime.isBefore(stsTokenGenTime)) { throw new XAdESValidationException("SigAndRefsTimeStamp before SignatureTimeStamp"); } } } long maxGracePeriod = this.documentContext.getMaxGracePeriod(); for (TimeStampToken sigAndRefsTimeStampToken : sigAndRefsTimeStampTokens) { DateTime sigAndRefsTokenGenTime = new DateTime( sigAndRefsTimeStampToken.getTimeStampInfo().getGenTime()); try { XAdESUtils.checkCloseEnough(signingTime, sigAndRefsTokenGenTime, maxGracePeriod * 1000 * 60 * 60); } catch (XAdESValidationException e) { throw new XAdESValidationException("SigAndRefsTimeStamp too far from SigningTime", e); } } // XAdES-X-L /* * Retrieve certificate chain and revocation data from XAdES-X-L * extension for trust validation. */ RevocationValuesType revocationValues = XAdESUtils.findUnsignedSignatureProperty(qualifyingProperties, RevocationValuesType.class, "RevocationValues"); List<X509CRL> crls = XAdESUtils.getCrls(revocationValues); List<OCSPResp> ocspResponses = XAdESUtils.getOCSPResponses(revocationValues); CertificateValuesType certificateValues = XAdESUtils.findUnsignedSignatureProperty(qualifyingProperties, CertificateValuesType.class, "CertificateValues"); if (null == certificateValues) { throw new XAdESValidationException("no CertificateValues element found."); } List<X509Certificate> certificateChain = XAdESUtils.getCertificates(certificateValues); if (certificateChain.isEmpty()) { throw new XAdESValidationException("no cert chain in CertificateValues"); } /* * Check certificate chain is indeed contains the signing * certificate. */ if (!Arrays.equals(signingCertificate.getEncoded(), certificateChain.get(0).getEncoded())) { // throw new XAdESValidationException( // "XAdES certificate chain does not include actual signing certificate"); /* * Not all XAdES implementations add the entire certificate * chain via xades:CertificateValues. */ certificateChain.add(0, signingCertificate); } LOG.debug("XAdES certificate chain contains actual signing certificate"); // XAdES-C CompleteCertificateRefsType completeCertificateRefs = XAdESUtils.findUnsignedSignatureProperty( qualifyingProperties, CompleteCertificateRefsType.class, "CompleteCertificateRefs"); if (null == completeCertificateRefs) { throw new XAdESValidationException("missing CompleteCertificateRefs"); } CompleteRevocationRefsType completeRevocationRefs = XAdESUtils.findUnsignedSignatureProperty( qualifyingProperties, CompleteRevocationRefsType.class, "CompleteRevocationRefs"); if (null == completeRevocationRefs) { throw new XAdESValidationException("missing CompleteRevocationRefs"); } for (OCSPResp ocspResp : ocspResponses) { XAdESUtils.checkReference(ocspResp, completeRevocationRefs); } for (X509CRL crl : crls) { XAdESUtils.checkReference(crl, completeRevocationRefs); } Iterator<X509Certificate> certIterator = certificateChain.iterator(); certIterator.next(); // digestion of SigningCertificate already // checked while (certIterator.hasNext()) { X509Certificate certificate = certIterator.next(); XAdESUtils.checkReference(certificate, completeCertificateRefs); } /* * Perform trust validation via eID Trust Service */ this.documentContext.validate(certificateChain, signingTime.toDate(), ocspResponses, crls); /* * Retrieve the possible eID identity signature extension data. */ String firstName = null; String name = null; String middleName = null; SignatureInfo.Gender gender = null; byte[] photo = null; IdentityType identity = XAdESUtils.findIdentity(nsElement, xmlSignature, signatureElement); if (null != identity) { firstName = identity.getFirstName(); name = identity.getName(); middleName = identity.getMiddleName(); switch (identity.getGender()) { case MALE: gender = SignatureInfo.Gender.MALE; break; case FEMALE: gender = SignatureInfo.Gender.FEMALE; break; } photo = identity.getPhoto().getValue(); } /* * Return the result of the signature analysis. */ return new SignatureInfo(signingCertificate, signingTime.toDate(), role, firstName, name, middleName, gender, photo); } catch (CertificateEncodingException e) { throw new XAdESValidationException(e); } catch (Exception e) { throw new XAdESValidationException(e); } }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") protected static String validarAssinaturaCMSeCarimboDeTempo(final byte[] digest, final String digestAlgorithm, final byte[] assinatura, Date dtAssinatura) throws InvalidKeyException, SecurityException, CRLException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, AplicacaoException, ChainValidationException, IOException, Exception { String nome = validarAssinaturaCMS(digest, digestAlgorithm, assinatura, dtAssinatura); Map<String, byte[]> map = new HashMap<String, byte[]>(); map.put(digestAlgorithm, digest);/*from w ww . j a v a 2 s. c o m*/ final CMSSignedData s = new CMSSignedData(map, assinatura); Collection ss = s.getSignerInfos().getSigners(); SignerInformation si = (SignerInformation) ss.iterator().next(); Attribute attr = si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken); CMSSignedData cmsTS = new CMSSignedData(attr.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded()); TimeStampToken tok = new TimeStampToken(cmsTS); Store cs = tok.getCertificates(); SignerId signer_id = tok.getSID(); BigInteger cert_serial_number = signer_id.getSerialNumber(); Collection certs = cs.getMatches(null); Iterator iter = certs.iterator(); X509Certificate certificate = null; while (iter.hasNext()) { X509Certificate cert = (X509Certificate) iter.next(); if (cert_serial_number != null) { if (cert.getSerialNumber().equals(cert_serial_number)) { certificate = cert; } } else { if (certificate == null) { certificate = cert; } } } tok.validate(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificate)); // Nato: falta validar as CRLs do carimbo de tempo if (!Arrays.equals(tok.getTimeStampInfo().getMessageImprintDigest(), MessageDigest.getInstance("SHA1").digest(si.getSignature()))) { throw new Exception("Carimbo de tempo no confere com o resumo do documento"); } try { validarAssinaturaCMS(null, null, cmsTS.getEncoded(), tok.getTimeStampInfo().getGenTime()); } catch (Exception e) { throw new Exception("Carimbo de tempo invlido!", e); } return nome; }
From source file:br.gov.jfrj.siga.cd.TimeStamper.java
License:Open Source License
private static TimeStampToken getTimeStampToken(byte[] content) throws Exception { TimeStampToken tsToken; boolean fSTF = true; if (!fSTF) {// w w w. j a v a 2 s . c om TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); reqGen.setCertReq(true); MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(content); byte[] assinatura = md.digest(); TimeStampRequest request = reqGen.generate(TSPAlgorithms.SHA1, assinatura); // TimeStampRequestGenerator reqGen = new // TimeStampRequestGenerator(); // // // request TSA to return certificate // reqGen.setCertReq(true); // // // Dummy request for sha1 // // Sha256 "2.16.840.1.101.3.4.2.1", // // TimeStampRequest request = reqGen.generate(TSPAlgorithms.SHA1, // MessageDigest.getInstance("SHA").digest(content)); byte[] reqData = request.getEncoded(); URL url; URLConnection urlConn; DataOutputStream printout; DataInputStream input; Properties systemProperties = System.getProperties(); systemProperties.setProperty("http.proxyHost", SigaCdProperties.getProxyHost()); systemProperties.setProperty("http.proxyPort", SigaCdProperties.getProxyPort()); // URL of CGI-Bin script. //url = new URL("http://www.edelweb.fr/cgi-bin/service-tsp"); url = new URL(SigaCdProperties.getTSPUrl()); // url = new URL("http://www.cryptopro.ru/tsp/tsp.srf"); // url = new URL("http://ns.szikszi.hu:8080/tsa"); // url = new URL("http://time.certum.pl/"); // URL connection channel. urlConn = url.openConnection(); // Let the run-time system (RTS) know that we want input. urlConn.setDoInput(true); // Let the RTS know that we want to do output. urlConn.setDoOutput(true); // No caching, we want the real thing. urlConn.setUseCaches(false); // Specify the content type. urlConn.setRequestProperty("Content-Type", "application/timestamp-query"); urlConn.setRequestProperty("Content-Length", String.valueOf(reqData.length)); // Send POST output. printout = new DataOutputStream(urlConn.getOutputStream()); printout.write(reqData); printout.flush(); printout.close(); // Get response data. input = new DataInputStream(urlConn.getInputStream()); // byte[] ba = streamToByteArray(input); TimeStampResponse response = new TimeStampResponse(input); input.close(); tsToken = response.getTimeStampToken(); } else { tsToken = gerarCarimboTempo(content); } SignerId signer_id = tsToken.getSID(); BigInteger cert_serial_number = signer_id.getSerialNumber(); System.out.println("Signer ID serial " + signer_id.getSerialNumber()); System.out.println("Signer ID issuer " + signer_id.getIssuer().toString()); Store cs = tsToken.getCertificates(); Collection certs = cs.getMatches(null); Iterator iter = certs.iterator(); X509Certificate certificate = null; while (iter.hasNext()) { X509Certificate cert = (X509Certificate) iter.next(); if (cert_serial_number != null) { if (cert.getSerialNumber().equals(cert_serial_number)) { System.out.println("using certificate with serial: " + cert.getSerialNumber()); System.out.println( "using certificate with base 64: " + Base64.encode(cert.getEncoded()) + "\n\n"); certificate = cert; } } else { if (certificate == null) { certificate = cert; } } System.out.println("Certificate subject dn " + cert.getSubjectDN()); System.out.println("Certificate serial " + cert.getSerialNumber()); } // Nato: validao do carimbo de tempo est desabilitada porque existe // um problema no certificado do STF if (!fSTF) tsToken.validate(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificate)); System.out.println("TS info " + tsToken.getTimeStampInfo().getGenTime()); System.out.println("TS info " + tsToken.getTimeStampInfo()); System.out.println("TS info " + tsToken.getTimeStampInfo().getAccuracy()); System.out.println("TS info " + tsToken.getTimeStampInfo().getNonce()); return tsToken; }
From source file:com.itextpdf.signatures.SignUtils.java
License:Open Source License
static Calendar getTimeStampDate(TimeStampToken timeStampToken) { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(timeStampToken.getTimeStampInfo().getGenTime()); return calendar; }
From source file:com.itextpdf.signatures.TSAClientBouncyCastle.java
License:Open Source License
/** * Get RFC 3161 timeStampToken.//ww w . ja v a2 s .c o m * Method may return null indicating that timestamp should be skipped. * @param imprint data imprint to be time-stamped * @return encoded, TSA signed data of the timeStampToken * @throws IOException * @throws TSPException */ public byte[] getTimeStampToken(byte[] imprint) throws IOException, TSPException { byte[] respBytes = null; // Setup the time stamp request TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator(); tsqGenerator.setCertReq(true); // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1"); BigInteger nonce = BigInteger.valueOf(SystemUtil.getSystemTimeMillis()); TimeStampRequest request = tsqGenerator.generate( new ASN1ObjectIdentifier(DigestAlgorithms.getAllowedDigest(digestAlgorithm)), imprint, nonce); byte[] requestBytes = request.getEncoded(); // Call the communications layer respBytes = getTSAResponse(requestBytes); // Handle the TSA response TimeStampResponse response = new TimeStampResponse(respBytes); // validate communication level attributes (RFC 3161 PKIStatus) response.validate(request); PKIFailureInfo failure = response.getFailInfo(); int value = (failure == null) ? 0 : failure.intValue(); if (value != 0) { // @todo: Translate value of 15 error codes defined by PKIFailureInfo to string throw new PdfException(PdfException.InvalidTsa1ResponseCode2).setMessageParams(tsaURL, String.valueOf(value)); } // @todo: validate the time stap certificate chain (if we want // assure we do not sign using an invalid timestamp). // extract just the time stamp token (removes communication status info) TimeStampToken tsToken = response.getTimeStampToken(); if (tsToken == null) { throw new PdfException(PdfException.Tsa1FailedToReturnTimeStampToken2).setMessageParams(tsaURL, response.getStatusString()); } TimeStampTokenInfo tsTokenInfo = tsToken.getTimeStampInfo(); // to view details byte[] encoded = tsToken.getEncoded(); LOGGER.info("Timestamp generated: " + tsTokenInfo.getGenTime()); if (tsaInfo != null) { tsaInfo.inspectTimeStampTokenInfo(tsTokenInfo); } // Update our token size estimate for the next call (padded to be safe) this.tokenSizeEstimate = encoded.length + 32; return encoded; }
From source file:com.itextpdf.text.pdf.security.TSAClientBouncyCastle.java
License:Open Source License
/** * Get RFC 3161 timeStampToken.// w w w. j a v a2s . com * Method may return null indicating that timestamp should be skipped. * @param imprint data imprint to be time-stamped * @return encoded, TSA signed data of the timeStampToken * @throws IOException * @throws TSPException */ public byte[] getTimeStampToken(byte[] imprint) throws IOException, TSPException { byte[] respBytes = null; // Setup the time stamp request TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator(); tsqGenerator.setCertReq(true); // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1"); BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); TimeStampRequest request = tsqGenerator.generate( new ASN1ObjectIdentifier(DigestAlgorithms.getAllowedDigests(digestAlgorithm)), imprint, nonce); byte[] requestBytes = request.getEncoded(); // Call the communications layer respBytes = getTSAResponse(requestBytes); // Handle the TSA response TimeStampResponse response = new TimeStampResponse(respBytes); // validate communication level attributes (RFC 3161 PKIStatus) response.validate(request); PKIFailureInfo failure = response.getFailInfo(); int value = (failure == null) ? 0 : failure.intValue(); if (value != 0) { // @todo: Translate value of 15 error codes defined by PKIFailureInfo to string throw new IOException(MessageLocalization.getComposedMessage("invalid.tsa.1.response.code.2", tsaURL, String.valueOf(value))); } // @todo: validate the time stap certificate chain (if we want // assure we do not sign using an invalid timestamp). // extract just the time stamp token (removes communication status info) TimeStampToken tsToken = response.getTimeStampToken(); if (tsToken == null) { throw new IOException(MessageLocalization.getComposedMessage( "tsa.1.failed.to.return.time.stamp.token.2", tsaURL, response.getStatusString())); } TimeStampTokenInfo tsTokenInfo = tsToken.getTimeStampInfo(); // to view details byte[] encoded = tsToken.getEncoded(); LOGGER.info("Timestamp generated: " + tsTokenInfo.getGenTime()); if (tsaInfo != null) { tsaInfo.inspectTimeStampTokenInfo(tsTokenInfo); } // Update our token size estimate for the next call (padded to be safe) this.tokenSizeEstimate = encoded.length + 32; return encoded; }