[英]Signing PDFs with iTextSharp Luna HSM - Hello world
我正在尝试使用Luna HSM签名PDF,并获得以下代码:
public class Sign
{
private const string _reason = "Test seal by eSignatur";
private const string _location = "Copenhagen, Denmark";
private const int _estimatedSize = 0;
private readonly X509Certificate2 _certificate;
private readonly ICollection<X509Certificate> _chain;
private readonly IOcspClient _ocspClient;
private readonly ICollection<ICrlClient> _crlList;
private readonly ITSAClient _tsaClient;
public Sign(X509Certificate2 certificate)
{
_certificate = certificate;
_chain = GetChain();
_ocspClient = new OcspClientBouncyCastle();
_crlList = new List<ICrlClient> { new CrlClientOnline(_chain) };
_tsaClient = GetTsaClient(_chain);
}
private ICollection<X509Certificate> GetChain()
{
var x509Store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
x509Store.Open(OpenFlags.ReadOnly);
var x509Chain = new X509Chain();
x509Chain.Build(_certificate);
var chain = (
from X509ChainElement x509ChainElement in x509Chain.ChainElements
select DotNetUtilities.FromX509Certificate(x509ChainElement.Certificate)).ToList();
x509Store.Close();
return chain;
}
private ITSAClient GetTsaClient(IEnumerable<X509Certificate> chain)
{
return (from cert in chain
select CertificateUtil.GetTSAURL(cert)
into tsaUrl
where tsaUrl != null
select new TSAClientBouncyCastle(tsaUrl)).FirstOrDefault();
}
public void Execute(string dest)
{
using (var reader = new PdfReader(GeneratePDF()))
{
using (var os = new FileStream(dest, FileMode.Create))
{
var stamper = PdfStamper.CreateSignature(reader, os, '\0');
var appearance = stamper.SignatureAppearance;
appearance.Reason = _reason;
appearance.Location = _location;
appearance.SetVisibleSignature(new Rectangle(0, 0, 0, 0), 1, string.Format("seal-{0}", DateTime.Now));
var pks = new X509Certificate2Signature(_certificate, DigestAlgorithms.SHA256);
MakeSignature.SignDetached(appearance, pks, _chain, _crlList, _ocspClient, _tsaClient, _estimatedSize, CryptoStandard.CMS);
}
}
}
}
然后,我将引用我已颁发的证书,该证书似乎已正确安装,并具有我可以使用certmgr.msc
查看的相应私钥。 我指的是它的指纹。
protected void Page_Load(object sender, EventArgs e)
{
var store = new X509Store(StoreLocation.CurrentUser);
try
{
store.Open(OpenFlags.ReadOnly);
var certificates = store.Certificates;
X509Certificate2 cert = null;
foreach (var certificate in certificates)
{
if (certificate.Thumbprint.ToString() == "123456")
{
cert = certificate;
}
}
Sign Signer = new Sign(cert);
Signer.Execute(string.Format(@"G:\Delete\{0}.pdf", DateTime.Now.ToString().Replace(":", "").Replace(@"/", "")));
}
finally
{
store.Close();
}
}
我收到以下错误:
“ / iText-HSM”应用程序中的服务器错误。 未定义键集。
说明:执行当前Web请求期间发生未处理的异常。 请查看堆栈跟踪,以获取有关错误及其在代码中起源的更多信息。
异常详细信息:System.Security.Cryptography.CryptographicException:未定义键集。
Source Error:
Line 97: appearance.SetVisibleSignature(new Rectangle(0, 0, 0, 0), 1, string.Format("seal-{0}", DateTime.Now));
Line 98:
Line 99: var pks = new X509Certificate2Signature(_certificate, DigestAlgorithms.SHA256);
Line 100: MakeSignature.SignDetached(appearance, pks, _chain, _crlList, _ocspClient, _tsaClient, _estimatedSize, CryptoStandard.CMS);
Line 101:
我真的很感谢我应该怎么做的一些指导,即我使用的证书正确吗?
提前谢谢了
您可以尝试编译并运行以下示例应用程序,该示例应用程序使用从UI中选择的证书(和私钥)创建CMS签名:
using System;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
X509Store certStore = null;
X509Certificate2 signingCertificate = null;
// Select signing certificate
try
{
certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = X509Certificate2UI.SelectFromCollection(certStore.Certificates, null, null, X509SelectionFlag.SingleSelection);
if (certCollection == null || certCollection.Count < 1)
throw new Exception("No certificate selected");
signingCertificate = certCollection[0];
if (!signingCertificate.HasPrivateKey)
throw new Exception("Selected certificate is not associated with a private key");
}
finally
{
if (certStore != null)
certStore.Close();
}
// Create CMS signature with selected certificate
byte[] dataToSign = Encoding.UTF8.GetBytes("Hello world");
ContentInfo contentInfo = new ContentInfo(dataToSign);
CmsSigner cmsSigner = new CmsSigner(signingCertificate);
SignedCms signedCms = new SignedCms(contentInfo, false);
signedCms.ComputeSignature(cmsSigner);
byte[] signature = signedCms.Encode();
// Parse and verify CMS signature (without certification path checking)
SignedCms signedCms2 = new SignedCms();
signedCms2.Decode(signature);
signedCms2.CheckSignature(true);
}
}
}
如果此应用程序无法创建签名,则很可能是您的HSM设置存在问题(例如,证书可能与私钥错误地配对)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.