.Net C# 取時戳伺服器的TimeStamp程式碼

服用前請先下載相關函式庫。

http://www.bouncycastle.org/csharp/

只需要下載bccrypto-net-1.7-bin.zip 已經足夠。

namespace com.test.util {

class TimeStamp {
public static void Main(string[] args) {

string error = “";
TimeStampToken tsToken = GetTimestampToken(“http://203.65.114.5/TSS/HttpTspServer", null, null, Encoding.UTF8.GetBytes(“Test"), ref error);
// Validation
ValidateTimestamp(tsToken);
byte[] bytes = tsToken.GetEncoded();

GetTSQuery(Encoding.UTF8.GetBytes(“Test"), “http://203.65.114.5/TSS/HttpTspServer");
}

public static byte[] GetTSQuery(byte[] stringBytes, string url) {
TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();
reqGen.SetCertReq(true);

TimeStampRequest tsReq = reqGen.Generate(TspAlgorithms.Sha1, SHA1CryptoServiceProvider.Create().ComputeHash(stringBytes), BigInteger.ValueOf(100));
byte[] tsData = tsReq.GetEncoded();

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = “POST";
req.ContentType = “application/timestamp-query";
req.Headers.Add(“Authorization", “Basic"); // “Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(“username:password")));
req.ContentLength = tsData.Length;

Stream reqStream = req.GetRequestStream();
reqStream.Write(tsData, 0, tsData.Length);
reqStream.Close();

HttpWebResponse res = (HttpWebResponse)req.GetResponse();
if (res == null) {
// return false;
return null;
} else {
Stream resStream = new BufferedStream(res.GetResponseStream());

TimeStampResponse tsRes = new TimeStampResponse(resStream);
resStream.Close();

try {
tsRes.Validate(tsReq);
PkiFailureInfo failure = tsRes.GetFailInfo();
if (failure != null && failure.IntValue !=0) {
Console.WriteLine(failure.IntValue);
return null;
}
return tsRes.GetEncoded();
} catch (TspException e) {
Console.WriteLine(e.Message);
// return false;
return null;
}
//saveresponse
}
}
public static TimeStampToken GetTimestampToken(String tsaURL, string tsaUserName, string tsaPassword, byte[] stringBytes, ref string error) {
TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
tsqGenerator.SetCertReq(true);
BigInteger nonce = BigInteger.ValueOf(DateTime.Now.Ticks);
TimeStampRequest request = tsqGenerator.Generate(Org.BouncyCastle.Asn1.X509.X509ObjectIdentifiers.IdSha1.Id, SHA1CryptoServiceProvider.Create().ComputeHash(stringBytes), nonce);
byte[] requestBytes = request.GetEncoded();
byte[] responseBytes = GetTSAResponse(tsaURL, tsaUserName, tsaPassword, requestBytes);
TimeStampResponse response = new TimeStampResponse(responseBytes);
response.Validate(request);

PkiFailureInfo failure = response.GetFailInfo();
int value = (failure == null) ? 0 : failure.IntValue;
if (value != 0) {
// error = string.Format(Resources.TSA_URL_ERROR, tsaURL, value);
return (null);
}
TimeStampToken tsToken = response.TimeStampToken;
if (tsToken == null) {
// error = string.Format(Resources.TSA_READ_ERROR, tsaURL);
return (null);
}

return tsToken;
}

public static byte[] GetTSAResponse(String tsaURL, string tsaUserName, string tsaPassword, byte[] requestBytes) {
Uri uri = new Uri(tsaURL);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.ContentType = “application/timestamp-query";
request.ContentLength = requestBytes.Length;
request.Method = “POST";
// if ((tsaUserName != null) && (tsaUserName != “")) {

// String userPassword = tsaUserName + “:" + tsaPassword;
CredentialCache credCache = new CredentialCache();
credCache.Add(new Uri(tsaURL), “Basic",
new NetworkCredential(tsaUserName, tsaPassword, tsaURL));
request.Credentials = credCache;
// }

Stream requestStream = request.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
WebResponse response = request.GetResponse();
Stream resStream = response.GetResponseStream();
MemoryStream ms = new MemoryStream();
byte[] responseBytes;
byte[] buffer = new byte[4096];
using (MemoryStream memoryStream = new MemoryStream()) {
int count = 0;
do {
count = resStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, count);

} while (count != 0);
responseBytes = memoryStream.ToArray();
}
response.Close();
return responseBytes;
}
public static bool ValidateTimestamp(TimeStampToken tst) { // Org.BouncyCastle.Tsp.TimeStampRequest tsq, Org.BouncyCastle.Tsp.TimeStampResponse tsr) {
// tsr.Validate(tsq);
// var tst = tsr.TimeStampToken;
DateTime timestamp = tst.TimeStampInfo.GenTime;
IEnumerable<Org.BouncyCastle.Cms.SignerInformation> signers = tst.ToCmsSignedData().GetSignerInfos().GetSigners().Cast<Org.BouncyCastle.Cms.SignerInformation>();
Org.BouncyCastle.X509.Store.IX509Store certs = tst.GetCertificates(“Collection");
foreach (var signer in signers) {
var signerCerts = certs.GetMatches(signer.SignerID).Cast<Org.BouncyCastle.X509.X509Certificate>().ToList();
if (signerCerts.Count != 1) {
throw new Exception(“Expected exactly one certificate for each signer in the timestamp");
return false;
}

if (!signerCerts[0].IsValid(timestamp)) {
throw new Exception(“The timestamp authority’s certificate is expired or not yet valid.");
return false;
}
if (!signer.Verify(signerCerts[0])) {
throw new Exception(“Invalid signature");
return false;
}
}
return true;
}
}
}

廣告

About fenjj

Perfect !!??...
本篇發表於 Uncategorized。將永久鏈結加入書籤。

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s