List of usage examples for org.bouncycastle.tsp TimeStampResponse TimeStampResponse
TimeStampResponse(DLSequence dlSequence) throws TSPException, IOException
From source file:com.itextpdf.text.pdf.TSAClientBouncyCastle.java
License:Open Source License
/** * Get timestamp token - Bouncy Castle request encoding / decoding layer *//* www. j ava 2 s. c om*/ protected byte[] getTimeStampToken(byte[] imprint) throws Exception { byte[] respBytes = null; try { // 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(X509ObjectIdentifiers.id_SHA1.getId(), 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 Exception(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 Exception(MessageLocalization.getComposedMessage( "tsa.1.failed.to.return.time.stamp.token.2", tsaURL, response.getStatusString())); } TimeStampTokenInfo info = tsToken.getTimeStampInfo(); // to view details byte[] encoded = tsToken.getEncoded(); long stop = System.currentTimeMillis(); // Update our token size estimate for the next call (padded to be safe) this.tokSzEstimate = encoded.length + 32; return encoded; } catch (Exception e) { throw e; } catch (Throwable t) { throw new Exception(MessageLocalization.getComposedMessage("failed.to.get.tsa.response.from.1", tsaURL), t); } }
From source file:com.opentrust.spi.pdf.PDFEnvelopedSignature.java
License:Mozilla Public License
public static TimestampToken addTSToCMS(CMSSignedDataWrapper cmsSignature, String algoId, ITspClient tspClient) throws NoSuchAlgorithmException, IOException, NoSuchFieldException, TSPException, CMSException { //byte[] tsResponse = getTSResponse2(cmsSignature.getSignatureValue(), user, password, serverTimestamp, algoId, policyId, useNonce); byte[] tsResponse; try {/*www. j a va 2s . c om*/ byte[] digest = DigestHelper.getDigest(cmsSignature.getSignatureValue(), algoId); byte[] fullresponse = tspClient.getRawTsp(digest, algoId); TimeStampResponse response = new TimeStampResponse(fullresponse); int status = response.getStatus(); if (status == GRANTED) { TimeStampToken tspValue = response.getTimeStampToken(); tsResponse = tspValue.getEncoded(); } else throw new RuntimeException( "Timestamping failure, status " + status + ", " + response.getStatusString()); } catch (Exception e) { throw new RuntimeException("Error getting timestamp from " + tspClient.getSource(), e); } TimestampToken timestampToken = new BCTimeStampToken(tsResponse); cmsSignature.appendSignatureTimeStamp(timestampToken.getEncoded()); return timestampToken; }
From source file:com.spilowagie.text.pdf.TSAClientBouncyCastle.java
License:Mozilla Public License
/** * Get timestamp token - Bouncy Castle request encoding / decoding layer */// w w w . ja v a 2s . com protected byte[] getTimeStampToken(byte[] imprint) throws Exception { byte[] respBytes = null; try { // 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(X509ObjectIdentifiers.id_SHA1.getId(), 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 Exception("Invalid TSA '" + tsaURL + "' response, code " + 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 Exception( "TSA '" + tsaURL + "' failed to return time stamp token: " + response.getStatusString()); } TimeStampTokenInfo info = tsToken.getTimeStampInfo(); // to view details byte[] encoded = tsToken.getEncoded(); long stop = System.currentTimeMillis(); // Update our token size estimate for the next call (padded to be safe) this.tokSzEstimate = encoded.length + 32; return encoded; } catch (Exception e) { throw e; } catch (Throwable t) { throw new Exception("Failed to get TSA response from '" + tsaURL + "'", t); } }
From source file:controller.Controller.java
private void getap() throws IOException, ParserConfigurationException, SAXException, TSPException { String xmlFilePath = "sign.xml"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document document = docBuilder.parse(new File(xmlFilePath)); Node signatureValueElement = document.getElementsByTagName("ds:SignatureValue").item(0); String out = signatureValueElement.getChildNodes().item(0).getNodeValue(); byte[] signatureValue = out.getBytes(); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); reqGen.setCertReq(true);// w w w .j av a2s .c o m TimeStampRequest tsReq = reqGen.generate(TSPAlgorithms.SHA1, signatureValue); byte[] tsData = tsReq.getEncoded(); String base64data = Base64.toBase64String(tsData); TS ts = new TS(); TSSoap soap = ts.getTSSoap(); String timestamp = soap.getTimestamp(base64data); if (timestamp == null) throw new WebServiceException("Webov sluba nedostupn"); byte[] responseB64 = timestamp.getBytes(); TimeStampResponse tsRes = new TimeStampResponse(Base64.decode(responseB64)); String decodedTimestamp = Base64.toBase64String(tsRes.getTimeStampToken().getEncoded()); System.out.println(decodedTimestamp); }
From source file:ec.rubrica.pdf.tsa.TSAClientBouncyCastleWithOid.java
License:Open Source License
/** * Se reimplementa este metodo para establecer un OID mediante el metodo * tsqGenerator.setReqPolicy()/*from w w w . jav a2s .c om*/ */ public byte[] getTimeStampToken(byte[] imprint) throws IOException, TSPException { byte[] respBytes = null; // Setup the time stamp request TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator(); tsqGenerator.setCertReq(true); // Se agrega una PID Policy: if (policy != null && policy.length() > 0) { tsqGenerator.setReqPolicy(new ASN1ObjectIdentifier(policy)); } BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); TimeStampRequest request = tsqGenerator.generate( new ASN1ObjectIdentifier(DigestAlgorithms.getAllowedDigests(getDigestAlgorithm())), 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())); } tsToken.getTimeStampInfo(); // to view details byte[] encoded = tsToken.getEncoded(); // Update our token size estimate for the next call (padded to be safe) this.tokenSizeEstimate = encoded.length + 32; return encoded; }
From source file:ec.rubrica.pdf.tsa.TSAClientBouncyCastleWithOid.java
License:Open Source License
/** * Se reimplementa este metodo para establecer un OID mediante el metodo * tsqGenerator.setReqPolicy()/*from w w w .ja v a 2s . c om*/ */ public byte[] getTimeStampToken54(byte[] imprint) throws IOException, TSPException { byte[] respBytes = null; // Setup the time stamp request TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator(); tsqGenerator.setCertReq(true); // Se agrega una PID Policy: if (policy != null && policy.length() > 0) { tsqGenerator.setReqPolicy(new ASN1ObjectIdentifier(policy)); } 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()); // QUITAR COMENTARIO: // 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:ee.ria.xroad.proxy.messagelog.TimestamperUtil.java
License:Open Source License
static TimeStampResponse getTimestampResponse(InputStream in) throws Exception { TimeStampResp response = TimeStampResp.getInstance(new ASN1InputStream(in).readObject()); if (response == null) { throw new RuntimeException("Could not read time-stamp response"); }/*from w ww. j a va2s .c o m*/ BigInteger status = response.getStatus().getStatus(); log.trace("getTimestampDer() - TimeStampResp.status: {}", status); if (!PKIStatus.granted.getValue().equals(status) && !PKIStatus.grantedWithMods.getValue().equals(status)) { PKIFreeText statusString = response.getStatus().getStatusString(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < statusString.size(); i++) { if (i > 0) { sb.append(", "); } sb.append("\"" + statusString.getStringAt(i) + "\""); } log.error("getTimestampDer() - TimeStampResp.status is not " + "\"granted\" neither \"grantedWithMods\": {}, {}", status, sb); throw new RuntimeException("TimeStampResp.status: " + status + ", .statusString: " + sb); } return new TimeStampResponse(response); }
From source file:ee.sk.digidoc.factory.SAXDigiDocFactory.java
License:Open Source License
/** * End Element handler/*w w w . j av a 2 s .co m*/ * @param namespaceURI namespace URI * @param lName local name * @param qName qualified name */ public void endElement(String namespaceURI, String sName, String qName) throws SAXException { if (m_logger.isDebugEnabled()) m_logger.debug("End Element: " + qName + " collect: " + m_nCollectMode); // remove last tag from stack String currTag = (String) m_tags.pop(); // collect SAX event data to original XML data // for <DataFile> we don't collect the begin and // end tags unless this an embedded <DataFile> StringBuffer sb = null; if (m_nCollectMode > 0 && (!qName.equals("DataFile") || m_nCollectMode > 1)) { sb = new StringBuffer(); sb.append("</"); sb.append(qName); sb.append(">"); } if (m_sbCollectSignature != null) { m_sbCollectSignature.append("</"); m_sbCollectSignature.append(qName); m_sbCollectSignature.append(">"); } // if we do cache in mem if (m_sbCollectChars != null && sb != null) m_sbCollectChars.append(sb.toString()); // </DataFile> if (qName.equals("DataFile")) { m_nCollectMode--; if (m_nCollectMode == 0) { // close DataFile cache if necessary try { if (m_dfCacheOutStream != null) { if (sb != null) m_dfCacheOutStream.write(ConvertUtils.str2data(sb.toString())); m_dfCacheOutStream.close(); m_dfCacheOutStream = null; } } catch (IOException ex) { SAXDigiDocException.handleException(ex); } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } DataFile df = m_doc.getLastDataFile(); System.out.println("End DF: " + df.getId() + " collect: " + m_nCollectMode); //debugWriteFile("DF-" + df.getId() + ".txt", m_sbCollectChars.toString()); if (df.getContentType().equals(DataFile.CONTENT_EMBEDDED)) { try { System.out.println("Set body: " + df.getId() + " -> " + m_sbCollectChars.toString()); if (df.getDfCacheFile() == null) df.setBody(ConvertUtils.str2data(sb.toString(), df.getInitialCodepage())); // canonicalize and calculate digest of body String str1 = sb.toString(); m_sbCollectChars = null; // check for whitespace before first tag of body int idx1 = 0; while (Character.isWhitespace(str1.charAt(idx1))) idx1++; //idx1 = str1.indexOf('<'); String str2 = null; if (idx1 > 0) { str2 = str1.substring(0, idx1); //System.out.println("prefix: \"" + str2 + "\""); updateDigest(str2.getBytes()); str2 = null; str1 = str1.substring(idx1); } // check for whitespace after the last xml tag of body idx1 = str1.length() - 1; while (Character.isWhitespace(str1.charAt(idx1))) idx1--; //idx1 = str1.lastIndexOf('>'); if (idx1 < str1.length() - 1) { str2 = str1.substring(idx1 + 1); //System.out.println("suffix: \"" + str2 + "\""); str1 = str1.substring(0, idx1 + 1); } //System.out.println("Body: \"" + str1 + "\""); //debugWriteFile("DF-" + df.getId() + "-body.txt", str1); // canonicalized body String str3 = null; if (str1.charAt(0) == '<') str3 = canonicalizeXml(str1); else str3 = str1; //System.out.println("Canonical: \"" + str3 + "\""); //debugWriteFile("DF-" + df.getId() + "-can.txt", str3); updateDigest(ConvertUtils.str2data(str3)); if (str2 != null) { updateDigest(ConvertUtils.str2data(str2)); str2 = null; } //calc digest over end tag updateDigest(ConvertUtils.str2data("</DataFile>")); df.setDigest(getDigest()); System.out.println("Digest: " + df.getId() + " - " + Base64Util.encode(df.getDigest())); m_sbCollectChars = null; // stop collecting //} catch(java.io.UnsupportedEncodingException ex) { //SAXDigiDocException.handleException(ex); } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } if (df.getContentType().equals(DataFile.CONTENT_EMBEDDED_BASE64)) { try { // calc digest over end tag updateDigest("</DataFile>".getBytes()); //System.out.println("Set digest: " + df.getId()); df.setDigest(getDigest()); System.out.println("Digest: " + df.getId() + " - " + Base64Util.encode(df.getDigest())); //System.out.println("Set body: " + df.getId()); if (df.getDfCacheFile() == null && sb != null) df.setBody(ConvertUtils.str2data(sb.toString(), df.getInitialCodepage())); m_sbCollectChars = null; // stop collecting } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } // this would throw away whitespace so calculate digest before it //df.setBody(Base64Util.decode(m_sbCollectChars.toString())); } //System.out.println("Done: " + df.getId()); m_bCollectDigest = false; } } // </SignedInfo> if (qName.equals("SignedInfo")) { if (m_nCollectMode > 0) m_nCollectMode--; // calculate digest over the original // XML form of SignedInfo block and save it try { Signature sig = getLastSignature(); SignedInfo si = sig.getSignedInfo(); //debugWriteFile("SigInfo1.xml", m_sbCollectChars.toString()); CanonicalizationFactory canFac = ConfigManager.instance().getCanonicalizationFactory(); byte[] bCanSI = canFac.canonicalize(ConvertUtils.str2data(m_sbCollectChars.toString(), "UTF-8"), SignedDoc.CANONICALIZATION_METHOD_20010315); si.setOrigDigest(SignedDoc.digest(bCanSI)); m_sbCollectChars = null; // stop collecting //debugWriteFile("SigInfo2.xml", si.toString()); } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } // </SignedProperties> if (qName.equals("SignedProperties")) { if (m_nCollectMode > 0) m_nCollectMode--; // calculate digest over the original // XML form of SignedInfo block and save it //debugWriteFile("SigProps-orig.xml", m_sbCollectChars.toString()); try { Signature sig = getLastSignature(); SignedProperties sp = sig.getSignedProperties(); String sigProp = m_sbCollectChars.toString(); //debugWriteFile("SigProp1.xml", sigProp); //System.out.println("SigProp1: " + sigProp.length() // + " digest: " + Base64Util.encode(SignedDoc.digest(sigProp.getBytes()))); CanonicalizationFactory canFac = ConfigManager.instance().getCanonicalizationFactory(); byte[] bCanProp = canFac.canonicalize(ConvertUtils.str2data(sigProp, "UTF-8"), SignedDoc.CANONICALIZATION_METHOD_20010315); //debugWriteFile("SigProp2.xml", new String(bCanProp)); sp.setOrigDigest(SignedDoc.digest(bCanProp)); //System.out.println("Digest: " + Base64Util.encode(SignedDoc.digest(bCanProp))); //System.out.println("SigProp2: " + sp.toString()); m_sbCollectChars = null; // stop collecting CertID cid = sig.getCertIdOfType(CertID.CERTID_TYPE_SIGNER); if (cid != null) { /*System.out.println("CID: " + cid.getId() + " serial: " + cid.getSerial() + " alg: " + cid.getDigestAlgorithm() + " diglen: " + ((cid.getDigestValue() == null) ? 0 : cid.getDigestValue().length));*/ if (cid.getId() != null) sp.setCertId(cid.getId()); else if (!sig.getSignedDoc().getVersion().equals(SignedDoc.VERSION_1_3)) sp.setCertId(sig.getId() + "-CERTINFO"); sp.setCertSerial(cid.getSerial()); sp.setCertDigestAlgorithm(cid.getDigestAlgorithm()); if (cid.getDigestValue() != null) { sp.setCertDigestValue(cid.getDigestValue()); } } } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } // </SignatureValue> if (qName.equals("SignatureValue")) { if (m_nCollectMode > 0) m_nCollectMode--; m_strSigValTs = m_sbCollectChars.toString(); //System.out.println("SigValTS mode: " + m_nCollectMode + "\n---\n" + m_strSigValTs + "\n---\n"); m_sbCollectChars = null; // stop collecting } // </CompleteRevocationRefs> if (qName.equals("CompleteRevocationRefs")) { if (m_nCollectMode > 0) m_nCollectMode--; if (m_sbCollectChars != null) m_strSigAndRefsTs = m_strSigValTs + m_sbCollectChars.toString(); //System.out.println("SigAndRefsTs mode: " + m_nCollectMode + "\n---\n" + m_strSigAndRefsTs + "\n---\n"); m_sbCollectChars = null; // stop collecting } // </Signature> if (qName.equals("Signature")) { if (m_nCollectMode == 0) { if (m_logger.isDebugEnabled()) m_logger.debug("End collecting <Signature>"); try { Signature sig = getLastSignature(); if (m_logger.isDebugEnabled()) m_logger.debug("Set sig content:\n---\n" + m_sbCollectSignature.toString() + "\n---\n"); if (m_sbCollectSignature != null) { sig.setOrigContent(ConvertUtils.str2data(m_sbCollectSignature.toString(), "UTF-8")); if (m_logger.isDebugEnabled()) m_logger.debug("SIG orig content set: " + sig.getId() + " len: " + ((sig.getOrigContent() == null) ? 0 : sig.getOrigContent().length)); //debugWriteFile("SIG-" + sig.getId() + ".txt", m_sbCollectSignature.toString()); m_sbCollectSignature = null; // reset collecting } } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } } // </SignatureTimeStamp> if (qName.equals("SignatureTimeStamp")) { if (m_logger.isDebugEnabled()) m_logger.debug("End collecting <SignatureTimeStamp>"); try { Signature sig = getLastSignature(); TimestampInfo ts = sig.getTimestampInfoOfType(TimestampInfo.TIMESTAMP_TYPE_SIGNATURE); if (ts != null && m_strSigValTs != null) { //System.out.println("SigValTS \n---\n" + m_strSigValTs + "\n---\n"); CanonicalizationFactory canFac = ConfigManager.instance().getCanonicalizationFactory(); byte[] bCanXml = canFac.canonicalize(ConvertUtils.str2data(m_strSigValTs, "UTF-8"), SignedDoc.CANONICALIZATION_METHOD_20010315); byte[] hash = SignedDoc.digest(bCanXml); //System.out.println("SigValTS hash: " + Base64Util.encode(hash)); //debugWriteFile("SigProp2.xml", new String(bCanProp)); ts.setHash(hash); } } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } // </SigAndRefsTimeStamp> if (qName.equals("SigAndRefsTimeStamp")) { if (m_logger.isDebugEnabled()) m_logger.debug("End collecting <SigAndRefsTimeStamp>"); try { Signature sig = getLastSignature(); TimestampInfo ts = sig.getTimestampInfoOfType(TimestampInfo.TIMESTAMP_TYPE_SIG_AND_REFS); if (ts != null && m_strSigAndRefsTs != null) { String canXml = "<a>" + m_strSigAndRefsTs + "</a>"; //System.out.println("SigAndRefsTS \n---\n" + m_strSigAndRefsTs + "\n---\n"); CanonicalizationFactory canFac = ConfigManager.instance().getCanonicalizationFactory(); byte[] bCanXml = canFac.canonicalize(ConvertUtils.str2data(canXml, "UTF-8"), SignedDoc.CANONICALIZATION_METHOD_20010315); canXml = new String(bCanXml, "UTF-8"); canXml = canXml.substring(3, canXml.length() - 4); //System.out.println("canonical \n---\n" + canXml + "\n---\n"); //debugWriteFile("SigProp2.xml", new String(bCanProp)); byte[] hash = SignedDoc.digest(ConvertUtils.str2data(canXml, "UTF-8")); //System.out.println("SigAndRefsTS hash: " + Base64Util.encode(hash)); ts.setHash(hash); } } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } catch (Exception ex) { //SAXDigiDocException.handleException(ex); } } // the following stuff is used also in // collect mode level 1 because it can be part // of SignedInfo or SignedProperties if (m_nCollectMode == 1) { // </SigningTime> if (qName.equals("SigningTime")) { try { Signature sig = getLastSignature(); SignedProperties sp = sig.getSignedProperties(); sp.setSigningTime(ConvertUtils.string2date(m_sbCollectItem.toString(), m_doc)); m_sbCollectItem = null; // stop collecting } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } // </ClaimedRole> if (qName.equals("ClaimedRole")) { Signature sig = getLastSignature(); SignedProperties sp = sig.getSignedProperties(); sp.addClaimedRole(m_sbCollectItem.toString()); m_sbCollectItem = null; // stop collecting } // </City> if (qName.equals("City")) { Signature sig = getLastSignature(); SignedProperties sp = sig.getSignedProperties(); SignatureProductionPlace spp = sp.getSignatureProductionPlace(); spp.setCity(m_sbCollectItem.toString()); m_sbCollectItem = null; // stop collecting } // </StateOrProvince> if (qName.equals("StateOrProvince")) { Signature sig = getLastSignature(); SignedProperties sp = sig.getSignedProperties(); SignatureProductionPlace spp = sp.getSignatureProductionPlace(); spp.setStateOrProvince(m_sbCollectItem.toString()); m_sbCollectItem = null; // stop collecting } // </CountryName> if (qName.equals("CountryName")) { Signature sig = getLastSignature(); SignedProperties sp = sig.getSignedProperties(); SignatureProductionPlace spp = sp.getSignatureProductionPlace(); spp.setCountryName(m_sbCollectItem.toString()); m_sbCollectItem = null; // stop collecting } // </PostalCode> if (qName.equals("PostalCode")) { Signature sig = getLastSignature(); SignedProperties sp = sig.getSignedProperties(); SignatureProductionPlace spp = sp.getSignatureProductionPlace(); spp.setPostalCode(m_sbCollectItem.toString()); m_sbCollectItem = null; // stop collecting } } // level 1 // the following is collected on any level // </DigestValue> if (qName.equals("DigestValue")) { try { //System.out.println("DIGEST: " + (m_sbCollectItem != null ? m_sbCollectItem.toString() : "NULL")); if (m_tags.search("Reference") != -1) { Signature sig = getLastSignature(); SignedInfo si = sig.getSignedInfo(); Reference ref = si.getLastReference(); ref.setDigestValue(Base64Util.decode(m_sbCollectItem.toString())); m_sbCollectItem = null; // stop collecting } else if (m_tags.search("SigningCertificate") != -1) { Signature sig = getLastSignature(); SignedProperties sp = sig.getSignedProperties(); sp.setCertDigestValue(Base64Util.decode(m_sbCollectItem.toString())); CertID cid = sig.getCertIdOfType(CertID.CERTID_TYPE_SIGNER); if (cid != null) cid.setDigestValue(Base64Util.decode(m_sbCollectItem.toString())); m_sbCollectItem = null; // stop collecting } else if (m_tags.search("CompleteCertificateRefs") != -1) { Signature sig = getLastSignature(); UnsignedProperties up = sig.getUnsignedProperties(); CompleteCertificateRefs crefs = up.getCompleteCertificateRefs(); CertID cid = crefs.getLastCertId(); if (cid != null) cid.setDigestValue(Base64Util.decode(m_sbCollectItem.toString())); //System.out.println("CertID: " + cid.getId() + " digest: " + m_sbCollectItem.toString()); m_sbCollectItem = null; // stop collecting } else if (m_tags.search("CompleteRevocationRefs") != -1) { Signature sig = getLastSignature(); UnsignedProperties up = sig.getUnsignedProperties(); CompleteRevocationRefs rrefs = up.getCompleteRevocationRefs(); rrefs.setDigestValue(Base64Util.decode(m_sbCollectItem.toString())); m_sbCollectItem = null; // stop collecting } } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } // </IssuerSerial> if (qName.equals("IssuerSerial") && !m_doc.getVersion().equals(SignedDoc.VERSION_1_3) && !m_doc.getVersion().equals(SignedDoc.VERSION_1_4)) { try { Signature sig = getLastSignature(); CertID cid = sig.getLastCertId(); if (cid != null) cid.setSerial(ConvertUtils.string2bigint(m_sbCollectItem.toString())); m_sbCollectItem = null; // stop collecting } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } // </X509SerialNumber> if (qName.equals("X509SerialNumber") && (m_doc.getVersion().equals(SignedDoc.VERSION_1_3) || m_doc.getVersion().equals(SignedDoc.VERSION_1_4))) { try { Signature sig = getLastSignature(); CertID cid = sig.getLastCertId(); if (cid != null) cid.setSerial(ConvertUtils.string2bigint(m_sbCollectItem.toString())); //System.out.println("X509SerialNumber: " + cid.getSerial() + " type: " + cid.getType()); m_sbCollectItem = null; // stop collecting } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } // </X509IssuerName> if (qName.equals("X509IssuerName") && (m_doc.getVersion().equals(SignedDoc.VERSION_1_3) || m_doc.getVersion().equals(SignedDoc.VERSION_1_4))) { try { Signature sig = getLastSignature(); CertID cid = sig.getLastCertId(); String s = m_sbCollectItem.toString(); if (cid != null) cid.setIssuer(s); //System.out.println("X509IssuerName: " + s + " type: " + cid.getType() + " nr: " + cid.getSerial()); m_sbCollectItem = null; // stop collecting } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } //</EncapsulatedTimeStamp> if (qName.equals("EncapsulatedTimeStamp")) { try { Signature sig = getLastSignature(); TimestampInfo ts = sig.getLastTimestampInfo(); try { //System.out.println("\n--TS_RESP--\n" + m_sbCollectItem.toString() + "\n--TS_RESP--\n"); ts.setTimeStampResponse(new TimeStampResponse(Base64Util.decode(m_sbCollectItem.toString()))); //ts.setTimeStampToken(new TimeStampToken(new CMSSignedData(Base64Util.decode(m_sbCollectItem.toString())))); } catch (TSPException ex) { throw new DigiDocException(DigiDocException.ERR_TIMESTAMP_RESP, "Invalid timestamp response", ex); } catch (IOException ex) { throw new DigiDocException(DigiDocException.ERR_TIMESTAMP_RESP, "Invalid timestamp response", ex); } m_sbCollectItem = null; // stop collecting } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } // </ResponderID> if (qName.equals("ResponderID")) { try { Signature sig = getLastSignature(); UnsignedProperties up = sig.getUnsignedProperties(); CompleteRevocationRefs rrefs = up.getCompleteRevocationRefs(); rrefs.setResponderId(m_sbCollectItem.toString()); m_sbCollectItem = null; // stop collecting } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } // </ProducedAt> if (qName.equals("ProducedAt")) { try { Signature sig = getLastSignature(); UnsignedProperties up = sig.getUnsignedProperties(); CompleteRevocationRefs rrefs = up.getCompleteRevocationRefs(); rrefs.setProducedAt(ConvertUtils.string2date(m_sbCollectItem.toString(), m_doc)); m_sbCollectItem = null; // stop collecting } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } // the following stuff is ignored in collect mode // because it can only be the content of a higher element //if (m_nCollectMode == 0) { // </SignatureValue> if (qName.equals("SignatureValue")) { try { Signature sig = getLastSignature(); SignatureValue sv = sig.getSignatureValue(); //debugWriteFile("SigVal.txt", m_sbCollectItem.toString()); //System.out.println("SIGVAL mode: " + m_nCollectMode + ":\n--\n" + (m_sbCollectItem != null ? m_sbCollectItem.toString() : "NULL")); sv.setValue(Base64Util.decode(m_sbCollectItem.toString().trim())); m_sbCollectItem = null; // stop collecting } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } // </X509Certificate> if (qName.equals("X509Certificate")) { try { Signature sig = getLastSignature(); CertValue cval = sig.getLastCertValue(); cval.setCert(SignedDoc.readCertificate(Base64Util.decode(m_sbCollectItem.toString()))); m_sbCollectItem = null; // stop collecting } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } // </EncapsulatedX509Certificate> if (qName.equals("EncapsulatedX509Certificate")) { try { Signature sig = getLastSignature(); CertValue cval = sig.getLastCertValue(); cval.setCert(SignedDoc.readCertificate(Base64Util.decode(m_sbCollectItem.toString()))); m_sbCollectItem = null; // stop collecting } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } // </EncapsulatedOCSPValue> if (qName.equals("EncapsulatedOCSPValue")) { try { Signature sig = getLastSignature(); // first we have to find correct certid and certvalue types findCertIDandCertValueTypes(sig); UnsignedProperties up = sig.getUnsignedProperties(); Notary not = up.getNotary(); not.setOcspResponseData(Base64Util.decode(m_sbCollectItem.toString())); NotaryFactory notFac = ConfigManager.instance().getNotaryFactory(); notFac.parseAndVerifyResponse(sig, not); // in 1.1 we had bad OCPS digest if (m_doc.getVersion().equals(SignedDoc.VERSION_1_1)) { CompleteRevocationRefs rrefs = up.getCompleteRevocationRefs(); rrefs.setDigestValue(SignedDoc.digest(not.getOcspResponseData())); } m_sbCollectItem = null; // stop collecting } catch (DigiDocException ex) { SAXDigiDocException.handleException(ex); } } //} // if(m_nCollectMode == 0) }
From source file:es.gob.afirma.signers.tsp.pkcs7.CMSTimestamper.java
License:Open Source License
/** Obtiene directamente el <i>token</i> de sello de tiempo según RFC3161. * @param imprint Huella digital de los datos sobre los que se quiere obtener el sello de tiempo * @param hashAlgorithm Algoritmo de huella digital usado para calcular la huella indicada en <code>imprint</code>. * @param time Tiempo de solicitud del sello. * @return <i>Token</i> de sello de tiempo según RFC3161. * @throws AOException Si se produce un error en el protocolo TSA o en ASN.1. * @throws IOException Si hay errores en la comunicación o en la lectura de datos con la TSA. */ public byte[] getTimeStampToken(final byte[] imprint, final String hashAlgorithm, final Calendar time) throws AOException, IOException { final TimeStampRequest request = this.tsqGenerator.generate( new ASN1ObjectIdentifier(hashAlgorithm != null ? AOAlgorithmID.getOID(hashAlgorithm) : X509ObjectIdentifiers.id_SHA1.getId()), imprint, BigInteger.valueOf(time != null ? time.getTimeInMillis() : System.currentTimeMillis())); final byte[] requestBytes = request.getEncoded(); final byte[] rawResponse = getTSAResponse(requestBytes); final TimeStampResponse response; try {//from w w w .java2 s . co m response = new TimeStampResponse(rawResponse); } catch (final Exception e) { throw new AOException("Error obteniendo la respuesta de la TSA: " + e, e); //$NON-NLS-1$ } // Validamos los atributos de la respuesta (RFC 3161 PKIStatus) try { response.validate(request); } catch (final Exception e) { throw new AOException("Error validando la respuesta de la TSA: " + e, e); //$NON-NLS-1$ } final PKIFailureInfo failure = response.getFailInfo(); final int value = failure == null ? 0 : failure.intValue(); if (value != 0) { throw new AOException("Respuesta invalida de la TSA ('" + this.tsaURL + "') con el codigo " + value); //$NON-NLS-1$ //$NON-NLS-2$ } // Extraemos el token de sello de tiempo (quitando la informacion de estado de las comunicaciones) final TimeStampToken tsToken = response.getTimeStampToken(); if (tsToken == null) { throw new AOException("La respuesta de la TSA ('" + this.tsaURL + "') no es un sello de tiempo valido: " //$NON-NLS-1$//$NON-NLS-2$ + new String(rawResponse)); } return tsToken.getEncoded(); }
From source file:es.mityc.firmaJava.ts.TSCliente.java
License:LGPL
/** * Este mtodo genera el Sello de Tiempo/*from w w w. j a va 2 s. c o m*/ * @param binarioaSellar fichero binario que se va a sellar * @return TimeStampToken en formato binario * @throws TSClienteError */ public byte[] generarSelloTiempo(byte[] binarioaSellar) throws TSClienteError { if (binarioaSellar == null) { log.error(MENSAJE_NO_DATOS_SELLO_TIEMPO); throw new TSClienteError(I18n.getResource(LIBRERIA_TSA_ERROR_1)); } else { log.info(MENSAJE_GENERANDO_SELLO_TIEMPO); TimeStampRequestGenerator generadorPeticion = new TimeStampRequestGenerator(); TimeStampRequest peticion = null; TimeStampResponse respuesta = null; try { MessageDigest resumen = MessageDigest.getInstance(algoritmoHash); resumen.update(binarioaSellar); peticion = generadorPeticion.generate(TSPAlgoritmos.getOID(algoritmoHash), resumen.digest()); log.info(MENSAJE_PETICION_TSA_GENERADA); } catch (Exception e) { log.error(MENSAJE_ERROR_PETICION_TSA); throw new TSClienteError(I18n.getResource(LIBRERIA_TSA_ERROR_10)); } cliente.getParams().setParameter(HttpClientParams.SO_TIMEOUT, INT5000); // Comprueba si hay configurado un proxy String servidorProxy = System.getProperty("http.proxyHost"); if (servidorProxy != null && !servidorProxy.trim().equals(CADENA_VACIA)) { int puertoProxy = 80; try { puertoProxy = Integer.parseInt(System.getProperty("http.proxyPort")); } catch (NumberFormatException ex) { } cliente.getHostConfiguration().setProxy(servidorProxy, puertoProxy); Credentials defaultcreds = new AuthenticatorProxyCredentials(servidorProxy, CADENA_VACIA); cliente.getState().setProxyCredentials(AuthScope.ANY, defaultcreds); } PostMethod metodo = new PostMethod(servidorTSA); metodo.addRequestHeader(CONTENT_TYPE, APPLICATION_TIMESTAMP_QUERY); ByteArrayInputStream datos = null; try { datos = new ByteArrayInputStream(peticion.getEncoded()); } catch (IOException e) { log.error(MENSAJE_ERROR_PETICION + e.getMessage()); throw new TSClienteError( I18n.getResource(LIBRERIA_TSA_ERROR_11) + DOS_PUNTOS_ESPACIO + e.getMessage()); } InputStreamRequestEntity rq = new InputStreamRequestEntity(datos); metodo.setRequestEntity(rq); metodo.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); byte[] cuerpoRespuesta = null; try { int estadoCodigo = cliente.executeMethod(metodo); log.info(MENSAJE_PETICION_TSA_ENVIADA); if (estadoCodigo != HttpStatus.SC_OK) { log.error(MENSAJE_FALLO_EJECUCION_METODO + metodo.getStatusLine()); throw new TSClienteError( I18n.getResource(LIBRERIA_TSA_ERROR_12) + DOS_PUNTOS_ESPACIO + metodo.getStatusLine()); } cuerpoRespuesta = metodo.getResponseBody(); log.info(MENSAJE_RESPUESTA_TSA_OBTENIDA); try { respuesta = new TimeStampResponse(cuerpoRespuesta); try { respuesta.validate(peticion); log.info(MENSAJE_RESPUESTA_TSA_VALIDADA_OK); // Para solucionar bug en libreria bouncycastle //return respuesta.getTimeStampToken().getEncoded(); //AppPerfect: Falso positivo ASN1InputStream is = new ASN1InputStream(cuerpoRespuesta); ASN1Sequence seq = ASN1Sequence.getInstance(is.readObject()); DEREncodable enc = seq.getObjectAt(1); if (enc == null) return null; return enc.getDERObject().getEncoded(); //Fin Para solucionar bug en libreria bouncycastle } catch (TSPException e) { log.error(MENSAJE_RESPUESTA_NO_VALIDA + e.getMessage()); throw new TSClienteError( I18n.getResource(LIBRERIA_TSA_ERROR_9) + DOS_PUNTOS_ESPACIO + e.getMessage()); } } catch (TSPException e) { log.error(MENSAJE_RESPUESTA_MAL_FORMADA + e.getMessage()); throw new TSClienteError( I18n.getResource(LIBRERIA_TSA_ERROR_8) + DOS_PUNTOS_ESPACIO + e.getMessage()); } catch (IOException e) { log.error(MENSAJE_SECUENCIA_BYTES_MAL_CODIFICADA + e.getMessage()); throw new TSClienteError( I18n.getResource(LIBRERIA_TSA_ERROR_7) + DOS_PUNTOS_ESPACIO + e.getMessage()); } } catch (HttpException e) { log.error(MENSAJE_VIOLACION_PROTOCOLO_HTTP + e.getMessage()); throw new TSClienteError( I18n.getResource(LIBRERIA_TSA_ERROR_6) + DOS_PUNTOS_ESPACIO + e.getMessage()); } catch (IOException e) { String mensajeError = I18n.getResource(LIBRERIA_TSA_ERROR_4) + DOS_PUNTOS_ESPACIO + servidorTSA; log.error(MENSAJE_ERROR_CONEXION_SERVIDOR_OCSP + e.getMessage()); throw new TSClienteError(mensajeError); } finally { // Termina la conexin metodo.releaseConnection(); } } }