【发布时间】:2020-10-09 18:08:05
【问题描述】:
我正在尝试使用智能卡中的私钥对一些数据进行签名。关键算法是 ECDSA。当我尝试获取私钥对象时,会发生系统不支持的异常。
经过一番研究,我知道 X509Certificate2 不支持 EC 密钥。
sysSec.X509Certificate2 cert = CertHelper.GetSignCertificate(serialNumber); //Get Certificate from Store var
key = cert.PrivateKey;
然后我尝试使用 Bouncy Castle 库。但是在这里我在解析 X509Certificate2 后无法获得 ECPrivateKeyParameters 。有一个代码:
byte[] pkcs12Bytes = cert.Export(sysSec.X509ContentType.Pkcs12,"test");
Pkcs12Store pkcs12 = new Pkcs12StoreBuilder().Build();
pkcs12.Load(new MemoryStream(pkcs12Bytes, false), "test".ToCharArray());
ECPrivateKeyParameters privKey = null;
foreach (string alias in pkcs12.Aliases)
{
if (pkcs12.IsKeyEntry(alias))
{
privKey = (ECPrivateKeyParameters)pkcs12.GetKey(alias).Key;
break;
}
}
它也不起作用。但是当我创建 CMS 文件时会发生奇怪的事情。有用。
public byte[] Sign(byte[] data , X509Certificate2 certificate ,bool detached )
{
if (data == null)
throw new ArgumentNullException("data");
if (certificate == null)
throw new ArgumentNullException("certificate");
// setup the data to sign
// ContentInfo content = new ContentInfo( new Oid("1.3.14.3.2.26"), data);
ContentInfo content = new ContentInfo( data);
SignedCms signedCms = new SignedCms(content, detached);
CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, certificate);
signer.SignedAttributes.Add(new Pkcs9DocumentName("testname"));
signer.SignedAttributes.Add(new Pkcs9SigningTime());
//signer.;
// CmsRecipientCollection recipest =new CmsRecipientCollection ()
// create the signature
signedCms.ComputeSignature(signer);
// signedCms.ComputeSignature()
byte[] res = signedCms.Encode();
foreach (SignerInfo info in signedCms.SignerInfos)
{
foreach (var item in info.SignedAttributes)
{
string frname = item.Oid.FriendlyName ?? "null";
Console.WriteLine(string.Format(" OID {0} : Value {1}", frname, item.Oid.Value.ToString()));
}
foreach (var item in info.UnsignedAttributes)
{
string frname = item.Oid.FriendlyName ?? "null";
Console.WriteLine(string.Format(" OID {0} : Value {1}", frname, item.Oid.Value.ToString()));
}
}
Console.WriteLine("Signed !");
return res;
}
那么有谁知道如何处理它? 还有如何使用 Bouncy Castle 从智能卡签名?
【问题讨论】:
-
你想使用
cert.GetECDsaPrivateKey(),它将使用内置提供程序(可以与智能卡对话)
标签: c# cryptography digital-signature smartcard ecdsa