首页新闻招聘找找看知识库

自签发X509证书,RSA解密时错误

0
悬赏园豆:30 [待解决问题]

1. 使用 vs cmd 执行命令以生成证书
->makecert -n "cn=MyTest" -pe -sr LocalMachine -ss my -a sha1 -b 09/13/2017 -e 09/13/2027 -r

2. 代码执行加解密测试

public static void Test(string subjectName, string plainText)
{
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

X509Certificate2Collection collection = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, false);

foreach (X509Certificate2 x509 in collection)
{
using (RSACryptoServiceProvider publicKeyProvider = (RSACryptoServiceProvider)x509.PublicKey.Key)
{
byte[] bytes = Encoding.Unicode.GetBytes(plainText);
byte[] encryptedBytes = publicKeyProvider.Encrypt(bytes, false);

using (RSACryptoServiceProvider privateKeyProvider = (RSACryptoServiceProvider)x509.PrivateKey)
{
byte[] decryptedBytes = privateKeyProvider.Decrypt(encryptedBytes, false);

string aa2 = Encoding.UTF8.GetString(decryptedBytes);
}
}

x509.Reset();
}

store.Close();
}

3. 调用测试方法 Test("MyTest","string123abc")

4. 错误行:“byte[] decryptedBytes = privateKeyProvider.Decrypt(encryptedBytes, false);”

5. 异常信息:“不正确的项”

 

求教哪个步骤有错误,感谢大神?

Hsuwen的主页 Hsuwen | 初学一级 | 园豆:10
提问于:2017-09-13 13:08
< >
分享
所有回答(1)
0

参考:http://www.itstrike.cn/Question/878bf5eb-f946-4ace-9600-25a495473187.html

金琥 | 园豆:1674 (小虾三级) | 2017-09-14 14:04

感谢支持,编码的问题我尝试过。我也尝试直接用加密后得byte[]解密,也是如此的错误,如下片段:

public static string TEST(string subjiect, string plainText)
{
using (RSACryptoServiceProvider publicKeyProvider = (RSACryptoServiceProvider)CertificateManager.GetPublicKey(subjiect))
{
byte[] bytes = Encoding.UTF8.GetBytes(plainText);
byte[] encryptedBytes = publicKeyProvider.Encrypt(bytes, false);

using (RSACryptoServiceProvider privateKeyProvider = (RSACryptoServiceProvider)CertificateManager.GetPrivateKey(subjiect))
{
byte[] decryptedBytes = privateKeyProvider.Decrypt(encryptedBytes, false);

return Encoding.UTF8.GetString(decryptedBytes);
}
}
}

 

错误位置:“privateKeyProvider.Decrypt(encryptedBytes, false);”

Hsuwen | 园豆:10 (初学一级) | 2017-09-14 19:11
   您需要登录以后才能回答,未注册用户请先注册