【问题标题】:X509Certificate Decrypt ExceprionX509Certificate Decrypt Exceprion
【发布时间】:2020-02-07 09:24:42
【问题描述】:

我从认证机构获得了数字证书,并获得了带有私钥的 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;
        }

直到此刻,在 DecryptRsa 方法中,一切都按原样进行:

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

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

谁能帮帮我?

我研究了很多解决方案,但大多数私钥都导出到 .pfx 文件,并在这样的时候使用三参数 X509Certificate2 构造函数

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

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

【问题讨论】:

  • 有人有什么建议吗?

标签: c# x509certificate2


【解决方案1】:

如果堆栈跟踪中的错误是“密钥集不存在。”,那么您可能需要“管理私钥”中的私钥权限

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

Please check this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 2011-09-16
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 2011-03-24
    • 2023-03-04
    • 1970-01-01
    相关资源
    最近更新 更多