List of usage examples for org.bouncycastle.asn1.cmp PKIFailureInfo intValue
public int intValue()
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 ww w . j a v a2s .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 = 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:com.itextpdf.signatures.TSAClientBouncyCastle.java
License:Open Source License
/** * Get RFC 3161 timeStampToken./* ww w . j a v a 2 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./*from w w w . j a v a 2 s .c om*/ * 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; }
From source file:com.itextpdf.text.pdf.TSAClientBouncyCastle.java
License:Open Source License
/** * Get timestamp token - Bouncy Castle request encoding / decoding layer *//*from w w w. j a v a2s .c o m*/ 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.spilowagie.text.pdf.TSAClientBouncyCastle.java
License:Mozilla Public License
/** * Get timestamp token - Bouncy Castle request encoding / decoding layer *///from w w w . j a va2 s . c o m 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:ec.rubrica.pdf.tsa.TSAClientBouncyCastleWithOid.java
License:Open Source License
/** * Se reimplementa este metodo para establecer un OID mediante el metodo * tsqGenerator.setReqPolicy()/*ww w . j a va 2 s . c o m*/ */ 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 .java 2 s.com*/ */ 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: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 {/* w w w. j a v a 2s . 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:net.sf.keystore_explorer.crypto.signing.TimeStampingClient.java
License:Open Source License
/** * Get RFC 3161 timeStampToken./*from w ww . j a v a 2s. c o m*/ * * @param tsaUrl Location of TSA * @param data The data to be time-stamped * @param hashAlg The algorithm used for generating a hash value of the data to be time-stamped * @return encoded, TSA signed data of the timeStampToken * @throws IOException */ public static byte[] getTimeStampToken(String tsaUrl, byte[] data, DigestType hashAlg) throws IOException { TimeStampResponse response = null; try { // calculate hash value MessageDigest digest = MessageDigest.getInstance(hashAlg.jce()); byte[] hashValue = digest.digest(data); // Setup the time stamp request TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator(); tsqGenerator.setCertReq(true); BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); TimeStampRequest request = tsqGenerator.generate(new ASN1ObjectIdentifier(hashAlg.oid()), hashValue, nonce); byte[] requestBytes = request.getEncoded(); // send http request byte[] respBytes = queryServer(tsaUrl, requestBytes); // process response 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) { throw new IOException("Server returned error code: " + String.valueOf(value)); } } catch (NoSuchAlgorithmException e) { throw new IOException(e); } catch (TSPException e) { throw new IOException(e); } // extract the time stamp token TimeStampToken tsToken = response.getTimeStampToken(); if (tsToken == null) { throw new IOException("TSA returned no time stamp token: " + response.getStatusString()); } return tsToken.getEncoded(); }
From source file:org.apache.poi.poifs.crypt.dsig.services.TSPTimeStampService.java
License:Apache License
@SuppressWarnings("unchecked") public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception { // digest the message MessageDigest messageDigest = CryptoFunctions.getMessageDigest(signatureConfig.getTspDigestAlgo()); 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 av a 2 s .c o m*/ String requestPolicy = signatureConfig.getTspRequestPolicy(); if (requestPolicy != null) { requestGenerator.setReqPolicy(new ASN1ObjectIdentifier(requestPolicy)); } ASN1ObjectIdentifier digestAlgoOid = mapDigestAlgoToOID(signatureConfig.getTspDigestAlgo()); TimeStampRequest request = requestGenerator.generate(digestAlgoOid, digest, nonce); byte[] encodedRequest = request.getEncoded(); // create the HTTP POST request Proxy proxy = Proxy.NO_PROXY; if (signatureConfig.getProxyUrl() != null) { URL proxyUrl = new URL(signatureConfig.getProxyUrl()); String host = proxyUrl.getHost(); int port = proxyUrl.getPort(); proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, (port == -1 ? 80 : port))); } HttpURLConnection huc = (HttpURLConnection) new URL(signatureConfig.getTspUrl()).openConnection(proxy); if (signatureConfig.getTspUser() != null) { String userPassword = signatureConfig.getTspUser() + ":" + signatureConfig.getTspPass(); String encoding = DatatypeConverter .printBase64Binary(userPassword.getBytes(Charset.forName("iso-8859-1"))); huc.setRequestProperty("Authorization", "Basic " + encoding); } huc.setRequestMethod("POST"); huc.setConnectTimeout(20000); huc.setReadTimeout(20000); huc.setDoOutput(true); // also sets method to POST. huc.setRequestProperty("User-Agent", signatureConfig.getUserAgent()); huc.setRequestProperty("Content-Type", signatureConfig.isTspOldProtocol() ? "application/timestamp-request" : "application/timestamp-query"); // "; charset=ISO-8859-1"); OutputStream hucOut = huc.getOutputStream(); hucOut.write(encodedRequest); // invoke TSP service huc.connect(); int statusCode = huc.getResponseCode(); if (statusCode != 200) { LOG.log(POILogger.ERROR, "Error contacting TSP server ", signatureConfig.getTspUrl()); throw new IOException("Error contacting TSP server " + signatureConfig.getTspUrl()); } // HTTP input validation String contentType = huc.getHeaderField("Content-Type"); if (null == contentType) { throw new RuntimeException("missing Content-Type header"); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(huc.getInputStream(), bos); LOG.log(POILogger.DEBUG, "response content: ", bos.toString()); if (!contentType.startsWith(signatureConfig.isTspOldProtocol() ? "application/timestamp-response" : "application/timestamp-reply")) { throw new RuntimeException("invalid Content-Type: " + contentType); } if (bos.size() == 0) { throw new RuntimeException("Content-Length is zero"); } // TSP response parsing and validation TimeStampResponse timeStampResponse = new TimeStampResponse(bos.toByteArray()); timeStampResponse.validate(request); if (0 != timeStampResponse.getStatus()) { LOG.log(POILogger.DEBUG, "status: " + timeStampResponse.getStatus()); LOG.log(POILogger.DEBUG, "status string: " + timeStampResponse.getStatusString()); PKIFailureInfo failInfo = timeStampResponse.getFailInfo(); if (null != failInfo) { LOG.log(POILogger.DEBUG, "fail info int value: " + failInfo.intValue()); if (/*PKIFailureInfo.unacceptedPolicy*/(1 << 8) == failInfo.intValue()) { LOG.log(POILogger.DEBUG, "unaccepted policy"); } } throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus()); } TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken(); SignerId signerId = timeStampToken.getSID(); BigInteger signerCertSerialNumber = signerId.getSerialNumber(); X500Name signerCertIssuer = signerId.getIssuer(); LOG.log(POILogger.DEBUG, "signer cert serial number: " + signerCertSerialNumber); LOG.log(POILogger.DEBUG, "signer cert issuer: " + signerCertIssuer); // TSP signer certificates retrieval Collection<X509CertificateHolder> certificates = timeStampToken.getCertificates().getMatches(null); X509CertificateHolder signerCert = null; Map<X500Name, X509CertificateHolder> certificateMap = new HashMap<X500Name, X509CertificateHolder>(); for (X509CertificateHolder certificate : certificates) { if (signerCertIssuer.equals(certificate.getIssuer()) && signerCertSerialNumber.equals(certificate.getSerialNumber())) { signerCert = certificate; } certificateMap.put(certificate.getSubject(), certificate); } // TSP signer cert path building if (signerCert == null) { throw new RuntimeException("TSP response token has no signer certificate"); } List<X509Certificate> tspCertificateChain = new ArrayList<X509Certificate>(); JcaX509CertificateConverter x509converter = new JcaX509CertificateConverter(); x509converter.setProvider("BC"); X509CertificateHolder certificate = signerCert; do { LOG.log(POILogger.DEBUG, "adding to certificate chain: " + certificate.getSubject()); tspCertificateChain.add(x509converter.getCertificate(certificate)); if (certificate.getSubject().equals(certificate.getIssuer())) { break; } certificate = certificateMap.get(certificate.getIssuer()); } while (null != certificate); // verify TSP signer signature X509CertificateHolder holder = new X509CertificateHolder(tspCertificateChain.get(0).getEncoded()); DefaultCMSSignatureAlgorithmNameGenerator nameGen = new DefaultCMSSignatureAlgorithmNameGenerator(); DefaultSignatureAlgorithmIdentifierFinder sigAlgoFinder = new DefaultSignatureAlgorithmIdentifierFinder(); DefaultDigestAlgorithmIdentifierFinder hashAlgoFinder = new DefaultDigestAlgorithmIdentifierFinder(); BcDigestCalculatorProvider calculator = new BcDigestCalculatorProvider(); BcRSASignerInfoVerifierBuilder verifierBuilder = new BcRSASignerInfoVerifierBuilder(nameGen, sigAlgoFinder, hashAlgoFinder, calculator); SignerInformationVerifier verifier = verifierBuilder.build(holder); timeStampToken.validate(verifier); // verify TSP signer certificate if (signatureConfig.getTspValidator() != null) { signatureConfig.getTspValidator().validate(tspCertificateChain, revocationData); } LOG.log(POILogger.DEBUG, "time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime()); byte[] timestamp = timeStampToken.getEncoded(); return timestamp; }