我的项目包括使用PKS11(usb智能卡)签署PDF文件。
我需要的是:
1)插入USB智能卡(让操作系统在CurrentUser商店中加载证书(Windows))
2)调用一个应用程序,无需GUI,用加载的证书签署确定的PDF。
步骤2需要用户输入智能卡的PIN。现在这不是一个问题,我可以静态设置它用于测试目的。
我读过的帖子是:
checking-for-the-accessibility-of-smart-card-private-keys-in-windows-10
find-certificate-on-smartcard-currently-on-reader
load-a-smart-card-or-other-private-certificate-in-cryptoserviceprovider-for-sign
how-do-i-sign-a-pdf-document-using-a-certificate-from-the-windows-cert-store
sign-pdf-with-itextsharp-5-3-3-and-usb-token
// Set up the PDF IO
PdfReader reader = new PdfReader(@"C:\Users\martin\Documents\tosign.pdf");
PdfStamper stamper = PdfStamper.CreateSignature(reader,
new FileStream(@"C:\Users\martin\Documents\SignedPdf.pdf", FileMode.Create),
'\0');
PdfSignatureAppearance sap = stamper.SignatureAppearance;
sap.Reason = "For no apparent reason";
sap.Location = "Place";
var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
X509Certificate2 cert = fcollection[0];
BcX509.X509CertificateParser cp = new BcX509.X509CertificateParser();
Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] {
cp.ReadCertificate(cert.RawData)
};
Console.WriteLine(cert);
X509Certificate2 signatureCert = new X509Certificate2(cert);
IExternalSignature externalSignature = new X509Certificate2Signature(cert, "SHA-1");
MakeSignature.SignDetached(sap, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);
我收到运行时错误
System.ArgumentException:'未知的加密算法 System.Security.Cryptography.RSACng'
在
行IExternalSignature externalSignature = new X509Certificate2Signature(cert, "SHA-1");
我在某处读到了使用自定义代码实现externalSignature,具体取决于USB供应商。虽然在这里提到的所有帖子中,似乎该行应该没有问题。我试图将算法更改为SHA-256。此外,我一直在挖掘IExternalSignature接口的Github代码,试图抓住它。
理论上,我知道USB设备的私钥永远不可访问,因此我不能尝试使用" getprivatekey"方法种类。
实际上,我是一个MEAN堆栈和Python开发人员,我从未在C#中编码。