【问题标题】:X509Certificate2: Access denined when decrypting with privatekeyX509Certificate2:使用私钥解密时拒绝访问
【发布时间】:2018-08-16 03:52:21
【问题描述】:

我有以下代码用于(en/de)加密密钥,该密钥又用于加密放置在客户端标头中的字符串,其中一些应用程序可能缓存。 (它们包含敏感信息)。本例中的应用程序是在 IIS 上运行的 ASP .Net core 2.0。

使用公钥加密工作正常,但是当我尝试解密时抛出异常。

    private string DecryptKey(string key)
    {
        if (this.Certificate == null || string.IsNullOrEmpty(key))
            throw new Exception("A x509 certificate and string for decryption must be provided");

        // Get the string as bytes
        var encryptedBytes = Convert.FromBase64String(key);

        if (!Certificate.HasPrivateKey)
            throw new Exception("x509 certificate does not contain a private key for decryption");

        using (var rsa = Certificate.GetRSAPrivateKey())
        {
            var result = rsa.Decrypt(encryptedBytes, RSAEncryptionPadding.OaepSHA512); // **Exception is thrown here**
            return ASCIIEncoding.ASCII.GetString(result);
        }
    }

    private string EncryptKey(string key)
    {
        if (this.Certificate == null || string.IsNullOrEmpty(key))
            throw new Exception("A x509 certificate and string for decryption must be provided");

        // Get the string as bytes
        var bytes = ASCIIEncoding.ASCII.GetBytes(key);

        if (!Certificate.HasPrivateKey)
            throw new Exception("x509 certificate does not contain a private key for decryption");

        using (var rsa = Certificate.GetRSAPrivateKey())
        {
            var result = rsa.Encrypt(bytes, RSAEncryptionPadding.OaepSHA512);
            return Convert.ToBase64String(result);
        }
    }

    /// <summary>
    /// Returns a X509Certificate2 with the given name
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    protected X509Certificate2 GetX509Certificate(string name)
    {
        // Get the certificate store for the current user.
        var store = new X509Store(StoreLocation.LocalMachine);

        try
        {
            store.Open(OpenFlags.ReadOnly);

            // Place all certificates in an X509Certificate2Collection object.
            var certCollection = store.Certificates;

            var currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
            var signingCert = currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, name, false);

            if (signingCert.Count == 0)
                return null;

            return signingCert[0];
        }
        finally
        {
            store.Close();
        }
    }

异常:Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException:'访问被拒绝'

这是堆栈:

        at System.Security.Cryptography.RSACng.EncryptOrDecrypt(SafeNCryptKeyHandle key, Byte[] input, AsymmetricPaddingMode paddingMode, Void* paddingInfo, EncryptOrDecryptAction encryptOrDecrypt)
        at System.Security.Cryptography.RSACng.EncryptOrDecrypt(Byte[] data, RSAEncryptionPadding padding, EncryptOrDecryptAction encryptOrDecrypt)
        at System.Security.Cryptography.RSACng.Decrypt(Byte[] data, RSAEncryptionPadding padding)
        at VmeApi.Extensions.KeyEncryptService.DecryptKey(String key) in C:\Users\kevom\Source\Repos\VME\VME Management\Management Core Api\Extensions\AppSettings\KeyEncryptService.cs:line 69
        at VmeApi.Extensions.KeyEncryptService..ctor(String certName, String encryptedKey) in C:\Users\kevom\Source\Repos\VME\VME Management\Management Core Api\Extensions\AppSettings\KeyEncryptService.cs:line 31
        at Management_Core_Api.Startup.ConfigureServices(IServiceCollection services) in C:\Users\kevom\Source\Repos\VME\VME Management\Management Core Api\Startup.cs:line 83

我已尝试使用 mmc 为我的帐户、IUser 帐户和网络服务提供对证书私钥的完全访问权限并重新启动操作系统,但这并没有做任何事情。

【问题讨论】:

  • 你能看看能不能找到私钥吗?
  • 您是否曾经重新导入证书?如果是这样,那将重置权限。此外,私钥可能被标记为仅签名(不解密),这将(不幸地)给出相同的“拒绝访问”
  • @mahlatse 它有一个私钥,因为 'var rsa = Certificate.GetRSAPrivateKey()' 不会抛出 NullReferenceException。
  • @bartonjs 不,我没有重新导入证书,它在应用程序启动时导入一次并保存一个实例,(如果这就是你的意思)。否则,它会保存到 Localmachine 的证书集合中;不,它没有被标记为仅签名。
  • “导入”是指“从某个来源读取它并将其添加到 X509Store”。

标签: c# asp.net-mvc iis x509certificate2


【解决方案1】:

这可能有点长,所以我会把它作为答案,因为作为评论的格式可能不够,

尝试检查是否可以使用以下代码访问私钥

private static string FindKeyLocation(string keyFileName)
        {
            string firstLocation =
            Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
            string secondLocation = firstLocation + @"\Microsoft\Crypto\RSA\MachineKeys";
            string[] textArray1 = Directory.GetFiles(secondLocation, keyFileName);
            if (textArray1.Length > 0)
            {
                return secondLocation;
            }
            string thirdLocation =
            Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string forthLocation = thirdLocation + @"\Microsoft\Crypto\RSA\";
            textArray1 = Directory.GetDirectories(forthLocation);
            if (textArray1.Length > 0)
            {
                foreach (string fifthLocation in textArray1)
                {
                    textArray1 = Directory.GetFiles(fifthLocation, keyFileName);
                    if (textArray1.Length != 0)
                    {
                        return fifthLocation;
                    }
                }
            }
            return "Private key exists but is not accessible";
        }

您可以通过将证书文件名指定为

来使用代码
RSACryptoServiceProvider rsa = cert.PrivateKey as RSACryptoServiceProvider;

            if (rsa != null)
            {
                string keyfilepath =
                    FindKeyLocation(rsa.CspKeyContainerInfo.UniqueKeyContainerName);
            }

这段代码也许可以解释为什么解密可能不起作用,在代码中将用户添加到证书的完整方法看起来像这样

private static void AddAccessToCertificate(X509Certificate2 cert, string user)
        {
            RSACryptoServiceProvider rsa = cert.PrivateKey as RSACryptoServiceProvider;

            if (rsa != null)
            {
                string keyfilepath =
                    FindKeyLocation(rsa.CspKeyContainerInfo.UniqueKeyContainerName);

                FileInfo file = new FileInfo(keyfilepath + "\\" +
                    rsa.CspKeyContainerInfo.UniqueKeyContainerName);

                FileSecurity fs = file.GetAccessControl();

                NTAccount account = new NTAccount(user);
                fs.AddAccessRule(new FileSystemAccessRule(account,
                FileSystemRights.FullControl, AccessControlType.Allow));

                file.SetAccessControl(fs);
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多