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. 异常信息:“不正确的项”
求教哪个步骤有错误,感谢大神?
参考:http://www.itstrike.cn/Question/878bf5eb-f946-4ace-9600-25a495473187.html
感谢支持,编码的问题我尝试过。我也尝试直接用加密后得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);”