在使用Itextsharp和MakeSignature.SignDetached方法为PDF文件加时间戳时遇到问题。
没有时间戳,下面的代码工作正常。当我想用时间戳签名时抛出异常:
远程服务器返回错误:(504)网关超时。
Fiddler给了我那个回复标题:
HTTP / 1.1 504 Fiddler - 收到失败日期:星期一,2018年4月30日11:28:57 GMT内容类型:text / html; charset = UTF-8连接:关闭 缓存控制:无缓存,必须重新验证时间戳:14:28:57.430 [Fiddler] ReadResponse()失败:服务器未返回完整 响应此请求。服务器返回0字节。
public void SignPDF(byte[] pdf, SignData signData) //signData: my custom class, it's about sign image,location,size
{
string timeStampServer = "http://xxxxxxxx";
string timeStampUser = "xxxx";
string timeStampPass = "xxxx";
string cryptokiDLL = @"C:\Program Files\SafeNet\LunaClient\cryptoki.dll";
string tokenLabel = "xxx";
string pin = "xxxx";
string primaryKeyLabel = "xxxxx";
string certsDir = @"C:\CERTs";
iTextSharp.text.Image signImg = null;
iTextSharp.text.Rectangle signRec = null;
byte[] signedPDF = null;
string hash = null;
try
{
HashAlgorithm hashAlgorithm = HashAlgorithm.SHA256;
Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(cryptokiDLL, null, tokenLabel, pin, primaryKeyLabel, null, hashAlgorithm);
byte[] signingCertificate = pkcs11RsaSignature.GetSigningCertificate();//1460
List<byte[]> otherCertificates = new List<byte[]>();
foreach (string file in Directory.GetFiles(certsDir))
otherCertificates.Add(File.ReadAllBytes(file));
var chain = CertUtils.BuildCertPath(signingCertificate, otherCertificates).ToList();
ITSAClient tsaClient = new TSAClientBouncyCastle(timeStampServer, timeStampUser, timeStampPass);
IOcspClient ocspClient = new OcspClientBouncyCastle();
List<ICrlClient> crlList = new List<ICrlClient>();
crlList.Add(new CrlClientOnline(chain));
using (PdfReader pdfReader = new PdfReader(pdf))
{
using (MemoryStream msPDFfinal = new MemoryStream())
{
using (PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, msPDFfinal, '\0'))
{
PdfWriter writer = pdfStamper.Writer;
PdfSignatureAppearance appearance = pdfStamper.SignatureAppearance;
byte[] signImgBinary = signData.ImzaBinary;
int x = signData.X;
int y = signData.Y;
int scale = signData.Scale;
int pageNum = signData.PageNum;
signImg = iTextSharp.text.Image.GetInstance(signImgBinary);
signImg.ScalePercent(scale);
float imgX = (float)x;
float imgY = (float)y;
float scaledW = signImg.ScaledWidth;
float scaledH = signImg.ScaledHeight;
signRec = new iTextSharp.text.Rectangle(imgX, imgY, imgX + scaledW, imgY + scaledH);
appearance.Layer2Text = " ";
appearance.Image = signImg;
appearance.SetVisibleSignature(signRec, pageNum, "SIG");
//without timestamp, it is signing the pdf. Everything is ok.
//MakeSignature.SignDetached(appearance, pkcs11RsaSignature, chain, null, null, null, 0, CryptoStandard.CADES);
//it returns 504 error, no server response
MakeSignature.SignDetached(appearance, pkcs11RsaSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES);
}
signedPDF = msPDFfinal.ToArray();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
最后,根据这个链接 what is wrong with godaddy's timestamp server and itextsharp? 我添加了用户代理和http协议标头但没有任何更改,仍然收到错误。
protected internal virtual byte[] GetTSAResponse(byte[] requestBytes) {
HttpWebRequest con = (HttpWebRequest)WebRequest.Create(tsaURL);
con.UserAgent = "itextsharp";
con.ProtocolVersion = HttpVersion.Version10;
con.ContentLength = requestBytes.Length;
con.ContentType = "application/timestamp-query";
con.Method = "POST";
con.KeepAlive = true;
if ((tsaUsername != null) && !tsaUsername.Equals("") ) {
string authInfo = tsaUsername + ":" + tsaPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo), Base64FormattingOptions.None);
con.Headers["Authorization"] = "Basic " + authInfo;
}
Stream outp = con.GetRequestStream();
outp.Write(requestBytes, 0, requestBytes.Length);
outp.Close();