X509证书解密超越



我从一个认证机构获得了数字证书,我得到了一个带有私钥的USB贴纸。 在VisualStudio中,我制作了控制台应用程序,我想使用该证书测试加密和解密。为此,我使用了众所周知的代码:

private static string EncryptRSA(string input)
{
string outputMessage = String.Empty;
X509Certificate2 cert = GetCertificateFromStore("I find sertificate by Serial number");
using (RSACryptoServiceProvider csp = (RSACryptoServiceProvider) cert.PublicKey.Key)
{
byte[] byteData = Encoding.UTF8.GetBytes(input);
byte[] byteEncrypted = csp.Encrypt(byteData, false);
outputMessage = Convert.ToBase64String(byteEncrypted);
}
return izlaznaPoruka;
}
public static string DecryptRsa(string enkriptovan)
{
string text = string.Empty;
X509Certificate2 cert = GetCertificateFromStore("I find sertificate by Serial number");
using (RSACryptoServiceProvider csp = (RSACryptoServiceProvider) cert.PrivateKey)
{
byte[] byteEncrypted = Convert.FromBase64String(enkriptovan);
byte[] byteDecrypted = csp.Decrypt(byteEncrypted, false);
text = Encoding.UTF8.GetString(byteDecrypted);
}
return text;
}

一切都按应有的方式进行,直到这一刻,在方法 解密Rsa:

byte[] byteDecrypted = csp.Decrypt(byteEncrypted, false);

此时,我的身份验证客户端需要密码 - 我输入了正确的密码,然后弹出以下异常: mscorlib 中发生类型为"System.Security.Cryptography.CryptographicException"的未处理异常.dll 发生内部错误。

谁能帮我?

我研究了很多解决方案,但大多数私钥都导出到 .pfx 文件并使用三参数 X509Certificate2 构造函数,如下所示

X509Certificate2 cert = new X509Certificate2("myhost.pfx", "pass",
X509KeyStorageFlags.MachineKeySet); 

然后更改文件夹 ProgramData\Microsoft\Crypto\RSA\MachineKeys 的权限 我手动更改了文件夹权限。

如果堆栈跟踪中的错误是"密钥集不存在",则可能需要"管理私钥"中的私钥权限

  1. 使用面向本地计算机证书存储的"证书"管理单元创建Microsoft管理控制台 (MMC(。
  2. 展开 MMC 并选择"管理私钥">
  3. 在"安全"选项卡上,添加具有读取访问权限的池标识或 IIS 用户帐户。

请检查此

最新更新