System.Security.Cryptography.CngKey.Import 遇到:CryptographicException: 在编码或解码时出错

今天在做一个RSA生成签名时遇到异常。一路跟踪代码最终发现在CngKey cngKey = CngKey.Import(keyData, CngKeyBlobFormat.Pkcs8PrivateBlob);产生了异常,反馈内容如下:System.Security.Cryptography.CryptographicException: 在编码或解码时出错。

在 System.Security.Cryptography.NCryptNative.ImportKey(SafeNCryptProviderHandle provider, Byte[] keyBlob, String format)
在 System.Security.Cryptography.CngKey.Import(Byte[] keyBlob, String curveName, CngKeyBlobFormat format, CngProvider provider)
在 System.Security.Cryptography.CngKey.Import(Byte[] keyBlob, CngKeyBlobFormat format)

我将这部分内容提取出来,控制台调试,代码如下:


```c#
public static string RsaSign_doNet(string message,string privateKey)
        {           
           try
            {
                byte[] keyData = Convert.FromBase64String(privateKey);
                CngKey cngKey = CngKey.Import(keyData, CngKeyBlobFormat.Pkcs8PrivateBlob);
                using (RSACng rsa = new RSACng(cngKey))
                {
                    byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
                    return Convert.ToBase64String(rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return ex.ToString();
            }
            
        }


```c#
static void Main(string[] args)
        {
            string privateKey = "123456789abcdefghijklmnopqrstuvw";

            //string message = "POST\n/v3/pay/transactions/native\n1629706323\n06D36A6D0A024A93BC758E685B8AB10D\n{\"appid\":\"wxe5bc7a52d9c4dc84\",\"mchid\":\"1604357178\",\"description\":\"2021年武术比赛报名\",\"out_trade_no\":\"c8aee95996c0086024e4fd1dbe3ed609\",\"time_expire\":\"2022-08-23T16:12:00+08:00\",\"notify_url\":\"https://enroll.longxingtiyu.cn/WeChatPay/PayInfo\",\"amount\":{\"total\":55,\"currency\":\"CNY\"}}\n";

            string message = "123456";

            string result = SHA256WITHRSA_SIGN.RsaSign_doNet(message,privateKey);

            Console.WriteLine(result);

            Console.ReadKey();
        }



仍然报错:

img

操作系统是win10 , 开发环境是VS2019,.net 版本 4.7.2
求帮忙看一下,为啥会报错?是我的私钥格式有问题还是怎么滴?
或者谁遇到过类似问题?

你好,我是有问必答小助手,非常抱歉,本次您提出的有问必答问题,技术专家团超时未为您做出解答


本次提问扣除的有问必答次数,已经为您补发到账户,我们后续会持续优化,扩大我们的服务范围,为您带来更好地服务。