我正在尝试在存储数据库之前对字符串进行加密,我使用加密解密方法如下
private static readonly X509Certificate2 Cert = GetCert();
private static X509Certificate2 GetCert()
{
if (Store == null)
{
throw new NullReferenceException("Store is null");
}
Store.Open(OpenFlags.ReadOnly);
var collection = Store.Certificates.Find(X509FindType.FindBySubjectName, "TestCert", false);
if (collection == null || collection.Count == 0)
{
throw new NullReferenceException("No certs in store");
}
X509Certificate2 certificate = collection.Cast<X509Certificate2>().FirstOrDefault(cert => cert != null && cert.HasPrivateKey);
if (certificate == null)
{
throw new NullReferenceException("Cert is null");
}
Store.Close();
return certificate;
}
用于加密
public static string Encrypt(this string plainText)
{
using (var rsa = (RSACng)Cert.GetRSAPublicKey())
{
var data = Encoding.Unicode.GetBytes(plainText);
var encrypted = rsa.Encrypt(data,RSAEncryptionPadding.OaepSHA1);
return Convert.ToBase64String(encrypted);
}
}
用于解密
public static string Decrypt(this string cipherText)
{
using (var rsa = Cert.GetRSAPrivateKey())
{
var data = Convert.FromBase64String(cipherText);
var encrypted = rsa.Decrypt(data, RSAEncryptionPadding.OaepSHA1);
return Encoding.Unicode.GetString(encrypted);
}
}
问题是当我解密..引发异常说
时WindowsCryptographicException:密钥集不存在
出了什么问题?
谢谢