问题是,显然是SwissSign CSP(加密服务提供商;一个在Windows系统存储和硬件设备之间提供桥梁的层)在使用MSCAPI时选择了错误的私钥。
在MSCAPI中选择正确的私钥似乎没有解决方法。
因此,我决定使用PKCS11和NCryptroki库。这里是代码:
using Cryptware.NCryptoki;
using iTextSharp.text;
using iTextSharp.text.log;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
using Org.BouncyCastle.Security;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace _07SignWithPKCS11DLL
{
class Program
{
static void Main(string[] args)
{
LoggerFactory.GetInstance().SetLogger(new SysoLogger());
Cryptoki cryptoki = new Cryptoki("cvP11.dll");
cryptoki.Initialize();
SlotList slots = cryptoki.Slots;
if (slots.Count == 0)
{
Console.WriteLine("No slot available");
Console.ReadLine();
return;
}
Slot slot = slots[0];
if (!slot.IsTokenPresent)
{
Console.WriteLine("No token inserted in the slot: " + slots[0].Info.Description);
Console.ReadLine();
return;
}
Token token = slot.Token;
Session session = token.OpenSession(Session.CKF_SERIAL_SESSION, null, null);
int nRes = session.Login(Session.CKU_USER, "secret");
if (nRes != 0)
{
Console.WriteLine("Wrong PIN");
return;
}
CSignWithPKCS11SC.Smartcardsign(session, "PhilippEggerQualifiedSignature", "SwissSign_nonRep ");
session.Logout();
session.Close();
cryptoki.Finalize(IntPtr.Zero);
Console.ReadLine();
}
}
class CryptokiPrivateKeySignature : IExternalSignature
{
private readonly Cryptware.NCryptoki.Session session;
RSAPrivateKey privateKey;
public CryptokiPrivateKeySignature(Session session, String alias)
{
this.session = session;
CryptokiCollection template = new CryptokiCollection();
template.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_PRIVATE_KEY));
template.Add(new ObjectAttribute(ObjectAttribute.CKA_KEY_TYPE, Key.CKK_RSA));
template.Add(new ObjectAttribute(ObjectAttribute.CKA_LABEL, alias));
privateKey = (RSAPrivateKey)session.Objects.Find(template);
}
public String GetHashAlgorithm()
{
return "SHA1";
}
public String GetEncryptionAlgorithm()
{
return "RSA";
}
public byte[] Sign(byte[] message)
{
session.SignInit(Mechanism.SHA1_RSA_PKCS, privateKey);
return session.Sign(message);
}
}
class CSignWithPKCS11SC
{
public const String SRC = @"C:\Temp\test_to_sign.pdf";
public const String DEST = @"C:\Temp\test_to_sign-pkcs11.pdf";
public const String DLL = "c:/windows/system32/cvP11.dll";
public void Sign(String src, String dest, ICollection<Org.BouncyCastle.X509.X509Certificate> chain, Session session, String alias,
String digestAlgorithm, CryptoStandard subfilter, String reason, String location,
ICollection<ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize)
{
PdfReader reader = null;
PdfStamper stamper = null;
FileStream os = null;
try
{
reader = new PdfReader(src);
os = new FileStream(dest, FileMode.Create);
stamper = PdfStamper.CreateSignature(reader, os, '\0');
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
appearance.Reason = reason;
appearance.Location = location;
appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
IExternalSignature pks = new CryptokiPrivateKeySignature(session, alias);
MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter);
}
finally
{
if (reader != null)
reader.Close();
if (stamper != null)
stamper.Close();
if (os != null)
os.Close();
}
}
public static void Smartcardsign(Session session, String alias, String aliasPrivateKey)
{
CryptokiCollection template = new CryptokiCollection();
template.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_CERTIFICATE));
template.Add(new ObjectAttribute(ObjectAttribute.CKA_CERTIFICATE_TYPE, Certificate.CKC_X_509));
template.Add(new ObjectAttribute(ObjectAttribute.CKA_LABEL, alias));
Cryptware.NCryptoki.X509Certificate nCert = (Cryptware.NCryptoki.X509Certificate)session.Objects.Find(template);
if (nCert != null)
{
X509Certificate2 cert = Utils.ConvertCertificate(nCert);
ICollection<Org.BouncyCastle.X509.X509Certificate> chain = new List<Org.BouncyCastle.X509.X509Certificate>();
X509Chain x509chain = new X509Chain();
x509chain.Build(cert);
foreach (X509ChainElement x509ChainElement in x509chain.ChainElements)
{
chain.Add(DotNetUtilities.FromX509Certificate(x509ChainElement.Certificate));
}
IOcspClient ocspClient = new OcspClientBouncyCastle();
List<ICrlClient> crlList = new List<ICrlClient>();
crlList.Add(new CrlClientOnline(chain));
TSAClientBouncyCastle tsaClient = new TSAClientBouncyCastle("http://tsa.swisssign.net");
CSignWithPKCS11SC app = new CSignWithPKCS11SC();
Console.WriteLine("Logged in? " + session.IsLoggedIn);
app.Sign(SRC, DEST, chain, session, aliasPrivateKey, DigestAlgorithms.SHA256, CryptoStandard.CMS,
"Test", "Rheinau", crlList, ocspClient, tsaClient, 0);
}
else
{
Console.WriteLine("Certificate not found: " + alias);
}
}
}
}