使用iTextSharp Luna HSM签署PDF - Hello world

时间:2015-05-22 16:19:48

标签: c# pdf itextsharp hsm

我正在尝试使用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:     

我真的很感谢我应该做些什么,即我使用正确的证书?

非常感谢提前

1 个答案:

答案 0 :(得分:1)

您可以尝试编译并运行以下示例应用程序,该应用程序使用您从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设置存在问题(例如,证书可能与私钥错误配对)。