You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中RSACryptoServiceProvider解密报错(错误码31)求助

RSA解密调用Advapi32.CryptDecrypt时错误码31的问题

调用底层C++库Interop.Advapi32.CryptDecrypt时,RSACryptoServiceProvider.Decrypt方法执行失败,内部错误码为31,报错信息如下:

System.Security.Cryptography.CryptographicException: '系统连接的设备不能正常运转。'

异常调用栈:

System.Security.Cryptography.CapiHelper.DecryptKey(System.Security.Cryptography.SafeCapiKeyHandle, byte[], int, bool, out byte[])
System.Security.Cryptography.RSACryptoServiceProvider.Decrypt(byte[], bool)
Program.$.__Decrypt|0_0(string) in Program.cs

当前需调用旧设备依赖的老式C++ RSA实现,相关代码如下:

using System;
using System.Security.Cryptography;

var privKeyPem = File.ReadAllText(@"PrivKey.pem");
Decrypt(privKeyPem);

static string? Decrypt(string pemString)
{
    try
    {
        var cipherText = Convert.FromBase64String(@"...");
        
        var cspParams = new CspParameters
        {
            ProviderType = 1, // PROV_RSA_FULL
            KeyContainerName = "Test"
        };
            
        using (var rsaProvider = new RSACryptoServiceProvider(cspParams))
        {
            rsaProvider.ImportFromPem(pemString);
            
            var maxChunkSize = (rsaProvider.KeySize / 8);

            using (var ms = new MemoryStream())
            {
                for (var i = 0; i < cipherText.Length; i += maxChunkSize)
                {
                    var chunkSize = Math.Min(maxChunkSize, cipherText.Length - i);
                    var chunk = new byte[chunkSize];
                    Array.Copy(cipherText, i, chunk, 0, chunkSize);
                    
                    var decrypted = rsaProvider.Decrypt(chunk, false);  // 错误发生处!
                    ms.Write(decrypted, 0, decrypted.Length);
                }
                
                return Encoding.ASCII.GetString(ms.ToArray());
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("解密文件时发生异常。", ex);
    }

    return null;
}

已完成以下验证操作:

  • PEM密钥有效,OpenSSL验证显示“RSA key ok”
  • 数组大小符合解密要求(密钥长度/8)
  • fOAEP/填充参数设为false
  • 进程运行用户拥有密钥存储权限
  • 执行sfc /scannow未发现系统问题
  • 尝试修改过KeyContainerName
  • 代码符合同类示例规范
  • 尝试添加CspProviderFlags.UseMachineKeyStore等标志
  • RSACryptoServiceProvider置于using块中
  • 代码未采用多线程
  • 代码以x86(32位)编译

请问老式Advapi32代码是否会尝试与系统中的其他组件通信?

内容的提问来源于stack exchange,提问作者Cryptc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.02 04:33:10