Beispiel #1
0
        public byte[] GetTimeStampToken(byte[] imprint)
        {
            byte[] respBytes = null;

            var tsqGenerator = new TimeStampRequestGenerator();

            tsqGenerator.SetCertReq(true);

            tsqGenerator.SetReqPolicy("2.16.76.1.6.6");
            var nonce        = BigInteger.ValueOf(DateTime.Now.Ticks + Environment.TickCount);
            var request      = tsqGenerator.Generate(DigestAlgorithms.GetAllowedDigest(this.digestAlgorithm), imprint, nonce);
            var requestBytes = request.GetEncoded();

            respBytes = this.GetTsaResponse(requestBytes);

            var response = new TimeStampResponse(respBytes);

            response.Validate(request);

            var failure = response.GetFailInfo();
            var value   = (failure == null) ? 0 : failure.IntValue;

            if (value != 0)
            {
                //// @todo: Translate value of 15 error codes defined by PKIFailureInfo to string
                var mensagem = string.Format(
                    "invalid.tsa.1.response.code.2 {0} {1}",
                    this.url, response.GetStatusString());

                throw new IOException(mensagem);
            }

            //// @todo: validate the time stap certificate chain (if we want assure we do not sign using an invalid timestamp).

            var timeStampToken = response.TimeStampToken;

            if (timeStampToken == null)
            {
                var mensagem = string.Format("tsa.1.failed.to.return.time.stamp.token.2 {0} {1}",
                                             this.url, response.GetStatusString());
                throw new IOException(mensagem);
            }

            var timeStampInfo = timeStampToken.TimeStampInfo;
            var encoded       = timeStampToken.GetEncoded();

            Console.WriteLine("Timestamp generated: " + timeStampInfo.GenTime);

            if (this.tsaInfo != null)
            {
                this.tsaInfo.InspectTimeStampTokenInfo(timeStampInfo);
            }

            this.tokenSizeEstimate = encoded.Length + 32;

            return(encoded);
        }
Beispiel #2
0
 private byte[] GetTimestampToken(byte[] imprint)
 {
     byte[] numArray;
     try
     {
         Licensing.ShowDemoMessage();
         string value = (new Oid(this.TimeStamping.HashAlgorithm.ToString())).Value;
         TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
         timeStampRequestGenerator.SetCertReq(true);
         if (this.TimeStamping.PolicyOid != null)
         {
             timeStampRequestGenerator.SetReqPolicy(this.TimeStamping.PolicyOid.Value.ToString());
         }
         TimeStampRequest timeStampRequest = null;
         if (!this.TimeStamping.UseNonce)
         {
             timeStampRequest = timeStampRequestGenerator.Generate(value, imprint);
         }
         else
         {
             long       tickCount  = (long)Environment.TickCount;
             DateTime   now        = DateTime.Now;
             BigInteger bigInteger = BigInteger.ValueOf(tickCount + now.Ticks);
             timeStampRequest = timeStampRequestGenerator.Generate(value, imprint, bigInteger);
         }
         byte[]            tSAResponse       = this.GetTSAResponse(timeStampRequest.GetEncoded());
         TimeStampResponse timeStampResponse = new TimeStampResponse(tSAResponse);
         timeStampResponse.Validate(timeStampRequest);
         if ((timeStampResponse.GetFailInfo() == null ? 0 : 1) != 0)
         {
             string[] invalidTimeStampingResponse = new string[] { CustomExceptions.InvalidTimeStampingResponse, "Status: ", null, null, null };
             invalidTimeStampingResponse[2] = timeStampResponse.Status.ToString();
             invalidTimeStampingResponse[3] = "; Status information : ";
             invalidTimeStampingResponse[4] = timeStampResponse.GetStatusString();
             throw new WebException(string.Concat(invalidTimeStampingResponse));
         }
         if (timeStampResponse.TimeStampToken == null)
         {
             throw new WebException(CustomExceptions.InvalidTimeStampingResponse);
         }
         numArray = tSAResponse;
     }
     catch
     {
         throw;
     }
     return(numArray);
 }
Beispiel #3
0
        /// <summary>Get RFC 3161 timeStampToken.</summary>
        /// <remarks>
        /// Get RFC 3161 timeStampToken.
        /// Method may return null indicating that timestamp should be skipped.
        /// </remarks>
        /// <param name="imprint">data imprint to be time-stamped</param>
        /// <returns>encoded, TSA signed data of the timeStampToken</returns>
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Org.Bouncycastle.Tsp.TSPException"/>
        public virtual byte[] GetTimeStampToken(byte[] imprint)
        {
            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.GetSystemTimeTicks());
            TimeStampRequest request = tsqGenerator.Generate(new DerObjectIdentifier(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, value.ToString());
            }
            // @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.TimeStampToken;

            if (tsToken == null)
            {
                throw new PdfException(PdfException.Tsa1FailedToReturnTimeStampToken2).SetMessageParams(tsaURL, response.GetStatusString
                                                                                                            ());
            }
            TimeStampTokenInfo tsTokenInfo = tsToken.TimeStampInfo;

            // to view details
            byte[] encoded = tsToken.GetEncoded();
            LOGGER.Info("Timestamp generated: " + tsTokenInfo.GenTime);
            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);
        }
        /**
         * Get RFC 3161 timeStampToken.
         * 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
         */
        public virtual byte[] GetTimeStampToken(byte[] imprint)
        {
            byte[] respBytes = null;
            // Setup the time stamp request
            TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();

            tsqGenerator.SetCertReq(true);
            if (!string.IsNullOrEmpty(tsaReqPolicy))
            {
                tsqGenerator.SetReqPolicy(tsaReqPolicy);
            }
            // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1");
            BigInteger       nonce   = BigInteger.ValueOf(DateTime.Now.Ticks + Environment.TickCount);
            TimeStampRequest request = tsqGenerator.Generate(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, 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.TimeStampToken;

            if (tsToken == null)
            {
                throw new IOException(MessageLocalization.GetComposedMessage("tsa.1.failed.to.return.time.stamp.token.2", tsaURL, response.GetStatusString()));
            }
            TimeStampTokenInfo tsTokenInfo = tsToken.TimeStampInfo; // to view details

            byte[] encoded = tsToken.GetEncoded();

            LOGGER.Info("Timestamp generated: " + tsTokenInfo.GenTime);
            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);
        }
Beispiel #5
0
        /**
         * Get timestamp token - Bouncy Castle request encoding / decoding layer
         */
        protected internal byte[] GetTimeStampToken(byte[] imprint)
        {
            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(DateTime.Now.Ticks + Environment.TickCount);
            TimeStampRequest request = tsqGenerator.Generate(X509ObjectIdentifiers.IdSha1.Id, 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.TimeStampToken;

            if (tsToken == null)
            {
                throw new Exception("TSA '" + tsaURL + "' failed to return time stamp token: " + response.GetStatusString());
            }
            TimeStampTokenInfo info = tsToken.TimeStampInfo; // to view details

            byte[] encoded = tsToken.GetEncoded();

            // Update our token size estimate for the next call (padded to be safe)
            this.tokSzEstimate = encoded.Length + 32;
            return(encoded);
        }
Beispiel #6
0
        /// <summary>
        /// Creates timestamp from provided data.
        /// </summary>
        /// <returns>
        ///   <see cref="TimestampObject" />
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// Hash algorithm not provided.
        /// or
        /// TSA URL not provided.
        /// or
        /// Timestamp output format not provided.
        /// or
        /// Data for timestamping not provided.</exception>
        /// <exception cref="AbsoluteTimestamp.TimestampException">Cannot connect to TSA server.</exception>
        /// <exception cref="TspValidationException"></exception>
        public TimestampObject CreateTimestamp()
        {
            /* Check that everything has been provided */
            if (0 == this.hashAlgorithm)
            {
                throw new ArgumentNullException("Hash algorithm not provided.");
            }
            if (String.IsNullOrWhiteSpace(this.tsaPrimaryUrl) && String.IsNullOrWhiteSpace(this.tsaSecondaryUrl))
            {
                throw new ArgumentNullException("TSA URL not provided.");
            }
            if (0 == this.outputFormat)
            {
                throw new ArgumentNullException("Timestamp output format not provided.");
            }
            if (null == this.timestampData)
            {
                throw new ArgumentNullException("Data for timestamping not provided.");
            }

            /* Get hashed data */
            byte[] hashedData = this.timestampData.GetHashedData(this.hashAlgorithm);

            /* Generate request */
            TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();

            requestGenerator.SetCertReq(true);

            TimeStampRequest request = requestGenerator.Generate(new Oid(this.hashAlgorithm.ToString()).Value, hashedData);

            /* Get response */
            TimeStampResponse response = GetTimeStampResponse(request);

            /* Validate response */
            if (!(response.Status == 0 || response.Status == 1))
            {
                throw new TspValidationException(
                          string.Format("Invalid response, response status={0}, response status string={1}, response failure info={2}",
                                        response.Status, response.GetStatusString(), response.GetFailInfo().IntValue));
            }

            /*
             * Check this response against to see if it a well formed response for
             * the passed in request. It validates message imprint digests and message imprint algorithms.
             *
             * @param request the request to be checked against
             * @throws TspException if the request can not match this response.
             */
            response.Validate(request);

            TimeStampToken   token       = response.TimeStampToken;
            X509Certificate2 certificate = null;

            TimestampObject timestamp = new TimestampObject();

            /* Validate certificate */
            certificate = TimestampVerifier.ValidateCertificate(token, timestamp, minimumCertificateValidityPeriod);

            timestamp.HashAlgorithm = this.hashAlgorithm;
            timestamp.Timestamp     = Utils.GetTimestampForOutput(response, this.outputFormat, this.timestampData);

            return(timestamp);
        }