title: Verify RFC 3161 trusted timestamp
body: <p>In my build process, I want to include a timestamp from an RFC-3161-compliant TSA.  At run time, the code will verify this timestamp, preferably without the assistance of a third-party library.  (This is a .NET application, so I have standard hash and asymmetric cryptography functionality readily at my disposal.)</p>
  
  <p>RFC 3161, with its reliance on ASN.1 and X.690 and whatnot, is not simple to implement, so for now at least, I'm using Bouncy Castle to generate the TimeStampReq (request) and parse the TimeStampResp (response).  I just can't quite figure out how to validate the response.</p>
  
  <p>So far, I've figured out how to extract the signature itself, the public cert, the time the timestamp was created, and the message imprint digest and nonce that I sent (for build-time validation).  What I can't figure out is how to put this data together to generate the data that was hashed and signed.</p>
  
  <p>Here's a rough idea of what I'm doing and what I'm trying to do.  This is test code, so I've taken some shortcuts.  I'll have to clean a couple of things up and do them the right way once I get something that works.</p>
  
  <h3>Timestamp generation at build time:</h3>
  
  <pre class="lang-cs prettyprint-override"><code>// a lot of fully-qualified type names here to make sure it's clear what I'm using
  
  static void WriteTimestampToBuild(){
      var dataToTimestamp = Encoding.UTF8.GetBytes("The rain in Spain falls mainly on the plain");
      var hashToTimestamp = new System.Security.Cryptography.SHA1Cng().ComputeHash(dataToTimestamp);
      var nonce = GetRandomNonce();
      var tsr = GetTimestamp(hashToTimestamp, nonce, "http://some.rfc3161-compliant.server");
  
      var tst = tsr.TimeStampToken;
      var tsi = tst.TimeStampInfo;
  
      ValidateNonceAndHash(tsi, hashToTimestamp, nonce);
  
      var cms = tst.ToCmsSignedData();
  
      var signer =
          cms.GetSignerInfos().GetSigners()
          .Cast&lt;Org.BouncyCastle.Cms.SignerInformation&gt;().First();
          // TODO: handle multiple signers?
  
      var signature = signer.GetSignature();
  
      var cert =
          tst.GetCertificates("Collection").GetMatches(signer.SignerID)
          .Cast&lt;Org.BouncyCastle.X509.X509Certificate&gt;().First();
          // TODO: handle multiple certs (for one or multiple signers)?
  
      ValidateCert(cert);
  
      var timeString = tsi.TstInfo.GenTime.TimeString;
      var time = tsi.GenTime; // not sure which is more useful
      // TODO: Do I care about tsi.TstInfo.Accuracy or tsi.GenTimeAccuracy?
  
      var serialNumber = tsi.SerialNumber.ToByteArray(); // do I care?
  
      WriteToBuild(cert.GetEncoded(), signature, timeString/*or time*/, serialNumber);
      // TODO: Do I need to store any more values?
  }
  
  static Org.BouncyCastle.Math.BigInteger GetRandomNonce(){
      var rng = System.Security.Cryptography.RandomNumberGenerator.Create();
      var bytes = new byte[10]; // TODO: make it a random length within a range
      rng.GetBytes(bytes);
      return new Org.BouncyCastle.Math.BigInteger(bytes);
  }
  
  static Org.BouncyCastle.Tsp.TimeStampResponse GetTimestamp(byte[] hash, Org.BouncyCastle.Math.BigInteger nonce, string url){
      var reqgen = new Org.BouncyCastle.Tsp.TimeStampRequestGenerator();
      reqgen.SetCertReq(true);
      var tsrequest = reqgen.Generate(Org.BouncyCastle.Tsp.TspAlgorithms.Sha1, hash, nonce);
      var data = tsrequest.GetEncoded();
  
      var webreq = WebRequest.CreateHttp(url);
      webreq.Method = "POST";
      webreq.ContentType = "application/timestamp-query";
      webreq.ContentLength = data.Length;
      using(var reqStream = webreq.GetRequestStream())
          reqStream.Write(data, 0, data.Length);
      using(var respStream = webreq.GetResponse().GetResponseStream())
          return new Org.BouncyCastle.Tsp.TimeStampResponse(respStream);
  }
  
  static void ValidateNonceAndHash(Org.BouncyCastle.Tsp.TimeStampTokenInfo tsi, byte[] hashToTimestamp, Org.BouncyCastle.Math.BigInteger nonce){
      if(tsi.Nonce != nonce)
          throw new Exception("Nonce doesn't match.  Man-in-the-middle attack?");
  
      var messageImprintDigest = tsi.GetMessageImprintDigest();
  
      var hashMismatch =
          messageImprintDigest.Length != hashToTimestamp.Length ||
          Enumerable.Range(0, messageImprintDigest.Length).Any(i=&gt;
              messageImprintDigest[i] != hashToTimestamp[i]
          );
  
      if(hashMismatch)
          throw new Exception("Message imprint doesn't match.  Man-in-the-middle attack?");
  }
  
  static void ValidateCert(Org.BouncyCastle.X509.X509Certificate cert){
      // not shown, but basic X509Chain validation; throw exception on failure
      // TODO: Validate certificate subject and policy
  }
  
  static void WriteToBuild(byte[] cert, byte[] signature, string time/*or DateTime time*/, byte[] serialNumber){
      // not shown
  }
  </code></pre>
  
  <h3>Timestamp verification at run time (client site):</h3>
  
  <pre class="lang-cs prettyprint-override"><code>// a lot of fully-qualified type names here to make sure it's clear what I'm using
  
  static void VerifyTimestamp(){
      var timestampedData = Encoding.UTF8.GetBytes("The rain in Spain falls mainly on the plain");
      var timestampedHash = new System.Security.Cryptography.SHA1Cng().ComputeHash(timestampedData);
  
      byte[] certContents;
      byte[] signature;
      string time; // or DateTime time
      byte[] serialNumber;
  
      GetDataStoredDuringBuild(out certContents, out signature, out time, out serialNumber);
  
      var cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certContents);
  
      ValidateCert(cert);
  
      var signedData = MagicallyCombineThisStuff(timestampedHash, time, serialNumber);
      // TODO: What other stuff do I need to magically combine?
  
      VerifySignature(signedData, signature, cert);
  
      // not shown: Use time from timestamp to validate cert for other signed data
  }
  
  static void GetDataStoredDuringBuild(out byte[] certContents, out byte[] signature, out string/*or DateTime*/ time, out byte[] serialNumber){
      // not shown
  }
  
  static void ValidateCert(System.Security.Cryptography.X509Certificates.X509Certificate2 cert){
      // not shown, but basic X509Chain validation; throw exception on failure
  }
  
  static byte[] MagicallyCombineThisStuff(byte[] timestampedhash, string/*or DateTime*/ time, byte[] serialNumber){
      // HELP!
  }
  
  static void VerifySignature(byte[] signedData, byte[] signature, System.Security.Cryptography.X509Certificates.X509Certificate2 cert){
      var key = (RSACryptoServiceProvider)cert.PublicKey.Key;
      // TODO: Handle DSA keys, too
      var okay = key.VerifyData(signedData, CryptoConfig.MapNameToOID("SHA1"), signature);
      // TODO: Make sure to use the same hash algorithm as the TSA
      if(!okay)
          throw new Exception("Timestamp doesn't match!  Don't trust this!");
  }
  </code></pre>
  
  <p>As you might guess, where I think I'm stuck is the <code>MagicallyCombineThisStuff</code> function.</p>