我有一张智能卡,我需要用它签署一个文件。正如我在stackover中看到的那样,这是一个大问题。
我不能使用 RSACryptoServiceProvider,bkz 它不支持 RSA-SHA256 算法。
起初我使用 CAPICOM.dll ,如下面的代码,
SignedData sed = new SignedData();
sed.Content = "a"; // data to sign
Signer ser = new Signer();
ser.Certificate = cc;
string singnn = sed.Sign(ser, false, CAPICOM_ENCODING_TYPE.CAPICOM_ENCODE_BASE64);
但是没有公钥来验证我的签名值,我无法从 capicom.dll 获得验证密钥。
之后 ,
我使用了 X509Certificate2 和 RSACryptoServiceProvider ,如下面的代码,
X509Certificate2 certificate = new X509Certificate2();
// Access Personal (MY) certificate store of current user
X509Store my = new X509Store(StoreName.My, StoreLocation.CurrentUser);
my.Open(OpenFlags.ReadOnly);
// Find the certificate we'll use to sign
RSACryptoServiceProvider csp = null;
foreach (X509Certificate2 cert in my.Certificates)
{
if (cert.Subject.Contains(certSubject))
{
// We found it.
// Get its associated CSP and private key
certificate = cert;
csp = (RSACryptoServiceProvider)cert.PrivateKey;
}
}
if (csp == null)
{
throw new Exception("No valid cert was found");
}
// Hash the data
SHA1Managed sha1 = new SHA1Managed();
UnicodeEncoding encoding = new UnicodeEncoding();
byte[] data = encoding.GetBytes(text);
byte[] hash = sha1.ComputeHash(data);
//byte[] data = Encoding.UTF8.GetBytes(text);
//HashAlgorithm sha = new SHA256Managed();
//byte[] hash = sha.TransformFinalBlock(data, 0, data.Length);
string key = csp.ToXmlString(false);
// Sign the hash
csp.PersistKeyInCsp = true;
byte[] response = csp.SignData(data, CryptoConfig.MapNameToOID("SHA1"));
string signbase64 = Convert.ToBase64String(response);
它有效,但我需要使用 RSA-SHA256 算法签名。当我像这样更改哈希算法时
byte[] response = csp.SignData(data, CryptoConfig.MapNameToOID("SHA256"));
我得到一个
错误:“未指定的错误”。
那是我的问题,解决方案是什么,或者我应该使用哪个库?
谢谢你的建议。。