Search in sources :

Example 1 with TimeStampRequestGenerator

use of org.bouncycastle.tsp.TimeStampRequestGenerator in project pdfbox by apache.

the class TSAClient method getTimeStampToken.

/**
 * @param messageImprint imprint of message contents
 * @return the encoded time stamp token
 * @throws IOException if there was an error with the connection or data from the TSA server,
 *                     or if the time stamp response could not be validated
 */
public byte[] getTimeStampToken(byte[] messageImprint) throws IOException {
    digest.reset();
    byte[] hash = digest.digest(messageImprint);
    // 32-bit cryptographic nonce
    SecureRandom random = new SecureRandom();
    int nonce = random.nextInt();
    // generate TSA request
    TimeStampRequestGenerator tsaGenerator = new TimeStampRequestGenerator();
    tsaGenerator.setCertReq(true);
    ASN1ObjectIdentifier oid = getHashObjectIdentifier(digest.getAlgorithm());
    TimeStampRequest request = tsaGenerator.generate(oid, hash, BigInteger.valueOf(nonce));
    // get TSA response
    byte[] tsaResponse = getTSAResponse(request.getEncoded());
    TimeStampResponse response;
    try {
        response = new TimeStampResponse(tsaResponse);
        response.validate(request);
    } catch (TSPException e) {
        throw new IOException(e);
    }
    TimeStampToken token = response.getTimeStampToken();
    if (token == null) {
        throw new IOException("Response does not have a time stamp token");
    }
    return token.getEncoded();
}
Also used : TimeStampResponse(org.bouncycastle.tsp.TimeStampResponse) SecureRandom(java.security.SecureRandom) TimeStampRequestGenerator(org.bouncycastle.tsp.TimeStampRequestGenerator) TSPException(org.bouncycastle.tsp.TSPException) IOException(java.io.IOException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) TimeStampRequest(org.bouncycastle.tsp.TimeStampRequest)

Example 2 with TimeStampRequestGenerator

use of org.bouncycastle.tsp.TimeStampRequestGenerator in project poi by apache.

the class TSPTimeStampService method timeStamp.

@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);
    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(InetAddress.getByName(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);
    // also sets method to POST.
    huc.setDoOutput(true);
    huc.setRequestProperty("User-Agent", signatureConfig.getUserAgent());
    huc.setRequestProperty("Content-Type", signatureConfig.isTspOldProtocol() ? "application/timestamp-request" : // "; charset=ISO-8859-1");
    "application/timestamp-query");
    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() + ", had status code " + statusCode + "/" + huc.getResponseMessage());
        throw new IOException("Error contacting TSP server " + signatureConfig.getTspUrl() + ", had status code " + statusCode + "/" + huc.getResponseMessage());
    }
    // 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: ", HexDump.dump(bos.toByteArray(), 0, 0));
    if (!contentType.startsWith(signatureConfig.isTspOldProtocol() ? "application/timestamp-response" : "application/timestamp-reply")) {
        throw new RuntimeException("invalid Content-Type: " + contentType + // dump the first few bytes
        ": " + HexDump.dump(bos.toByteArray(), 0, 0, 200));
    }
    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());
    return timeStampToken.getEncoded();
}
Also used : DefaultCMSSignatureAlgorithmNameGenerator(org.bouncycastle.cms.DefaultCMSSignatureAlgorithmNameGenerator) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) X500Name(org.bouncycastle.asn1.x500.X500Name) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) URL(java.net.URL) TimeStampResponse(org.bouncycastle.tsp.TimeStampResponse) Proxy(java.net.Proxy) HttpURLConnection(java.net.HttpURLConnection) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) MessageDigest(java.security.MessageDigest) SignerInformationVerifier(org.bouncycastle.cms.SignerInformationVerifier) BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) SecureRandom(java.security.SecureRandom) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) TimeStampRequest(org.bouncycastle.tsp.TimeStampRequest) X509Certificate(java.security.cert.X509Certificate) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) PKIFailureInfo(org.bouncycastle.asn1.cmp.PKIFailureInfo) SignerId(org.bouncycastle.cms.SignerId) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) TimeStampRequestGenerator(org.bouncycastle.tsp.TimeStampRequestGenerator) BcRSASignerInfoVerifierBuilder(org.bouncycastle.cms.bc.BcRSASignerInfoVerifierBuilder) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 3 with TimeStampRequestGenerator

use of org.bouncycastle.tsp.TimeStampRequestGenerator in project signer by demoiselle.

the class TimeStampOperator method createRequest.

/**
 * Creates a time stamp request, signed with the users's certificate.
 *
 * @param privateKey private key to sign with
 * @param certificates certificate chain
 * @param content  set null if signing only hash
 * @param hash  set null if signing content
 * @return A time stamp request
 * @throws CertificateCoreException exception
 */
public byte[] createRequest(PrivateKey privateKey, Certificate[] certificates, byte[] content, byte[] hash) throws CertificateCoreException {
    try {
        logger.info(timeStampMessagesBundle.getString("info.timestamp.digest"));
        Digest digest = DigestFactory.getInstance().factoryDefault();
        digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
        byte[] hashedMessage = null;
        if (content != null) {
            hashedMessage = digest.digest(content);
        // logger.info(Base64.toBase64String(hashedMessage));
        } else {
            hashedMessage = hash;
        }
        logger.info(timeStampMessagesBundle.getString("info.timestamp.prepare.request"));
        TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
        timeStampRequestGenerator.setReqPolicy(new ASN1ObjectIdentifier(TimeStampConfig.getInstance().getTSPOid()));
        timeStampRequestGenerator.setCertReq(true);
        BigInteger nonce = BigInteger.valueOf(100);
        timeStampRequest = timeStampRequestGenerator.generate(new ASN1ObjectIdentifier(TSPAlgorithms.SHA256.getId()), hashedMessage, nonce);
        byte[] request = timeStampRequest.getEncoded();
        logger.info(timeStampMessagesBundle.getString("info.timestamp.sign.request"));
        RequestSigner requestSigner = new RequestSigner();
        byte[] signedRequest = requestSigner.signRequest(privateKey, certificates, request, "SHA256withRSA");
        return signedRequest;
    } catch (IOException ex) {
        throw new CertificateCoreException(ex.getMessage());
    }
}
Also used : Digest(org.demoiselle.signer.cryptography.Digest) BigInteger(java.math.BigInteger) TimeStampRequestGenerator(org.bouncycastle.tsp.TimeStampRequestGenerator) IOException(java.io.IOException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException) RequestSigner(org.demoiselle.signer.timestamp.signer.RequestSigner)

Example 4 with TimeStampRequestGenerator

use of org.bouncycastle.tsp.TimeStampRequestGenerator in project keystore-explorer by kaikramer.

the class TimeStampingClient method getTimeStampToken.

/**
 * Get RFC 3161 timeStampToken.
 *
 * @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();
}
Also used : IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) TimeStampRequest(org.bouncycastle.tsp.TimeStampRequest) PKIFailureInfo(org.bouncycastle.asn1.cmp.PKIFailureInfo) TimeStampResponse(org.bouncycastle.tsp.TimeStampResponse) BigInteger(java.math.BigInteger) TimeStampRequestGenerator(org.bouncycastle.tsp.TimeStampRequestGenerator) TSPException(org.bouncycastle.tsp.TSPException) MessageDigest(java.security.MessageDigest) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Aggregations

IOException (java.io.IOException)4 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)4 TimeStampRequestGenerator (org.bouncycastle.tsp.TimeStampRequestGenerator)4 BigInteger (java.math.BigInteger)3 TimeStampRequest (org.bouncycastle.tsp.TimeStampRequest)3 TimeStampResponse (org.bouncycastle.tsp.TimeStampResponse)3 TimeStampToken (org.bouncycastle.tsp.TimeStampToken)3 MessageDigest (java.security.MessageDigest)2 SecureRandom (java.security.SecureRandom)2 PKIFailureInfo (org.bouncycastle.asn1.cmp.PKIFailureInfo)2 TSPException (org.bouncycastle.tsp.TSPException)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 OutputStream (java.io.OutputStream)1 HttpURLConnection (java.net.HttpURLConnection)1 InetSocketAddress (java.net.InetSocketAddress)1 Proxy (java.net.Proxy)1 URL (java.net.URL)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 X509Certificate (java.security.cert.X509Certificate)1 ArrayList (java.util.ArrayList)1