【发布时间】:2016-04-06 16:49:27
【问题描述】:
我想用证书签署一个文件。我编写了以下代码,但出现“文件内容错误”,而且我总是询问私钥。 我做错了什么?如何发送私钥? 谢谢大家。
string cSerial = "0C4744041F40B761322124EB691C5F32";
//Find my certificate with serial
X509Store my = new X509Store(StoreName.My, StoreLocation.CurrentUser);
my.Open(OpenFlags.ReadOnly);
System.Security.Cryptography.RSACryptoServiceProvider csp = null;
foreach (X509Certificate2 cert in my.Certificates)
{
if (cert.SerialNumber.Trim() == cSerial)
{ csp = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey; }
}
//Here i have the certificate, it's ok.
System.Security.Cryptography.SHA1Managed sha1 = new System.Security.Cryptography.SHA1Managed();
UnicodeEncoding encoding = new UnicodeEncoding();
//////////byte[] data = encoding.GetBytes("test.xml");
byte[] data = File.ReadAllBytes("test.xml")
byte[] hash = sha1.ComputeHash(data);
byte[] aa = csp.SignHash(hash, System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA1"));
File.WriteAllBytes("text.p7m", aa);
my.Close();
【问题讨论】:
-
UnicodeEncoding.GetBytes 不读取文件。它只是将字符串“text.xml”中的字节编码为字节数组。
-
@Kevin,我编辑了我的源,但结果没有改变......谢谢。
-
使用调试器找出是哪一行产生了错误。
-
我用 BouncyCastle 解决了这个问题。
标签: c# x509certificate2