public string SignSHA256RSA(string data,string privateKey)
{
using (var rsa = RSA.Create())
{
byte[] privateKeyBytes = Convert.FromBase64String(privateKey);
rsa.ImportPkcs8PrivateKey(privateKeyBytes, out _);
var dataToSign = Encoding.UTF8.GetBytes(data);
var signature = rsa.SignData(dataToSign, HashAlgorithmName.SHA256, RSASignaturePadding.Pss);
return Convert.ToBase64String(signature);
}
}
使用上面的代码,我尝试使用某个私钥生成RSA签名。在本地运行很流畅,但是当我发布到服务器时,会产生以下错误:
Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: The system cannot find the file specified.
at System.Security.Cryptography.CngKeyLite.ImportKeyBlob(String blobType, ReadOnlySpan keyBlob, Boolean encrypted, ReadOnlySpan password)
at System.Security.Cryptography.CngPkcs8.ImportPkcs8(ReadOnlySpan keyBlob)
at System.Security.Cryptography.CngPkcs8.ImportPkcs8PrivateKey(ReadOnlySpan source, Int32& bytesRead)
at System.Security.Cryptography.RSAImplementation.RSACng.ImportPkcs8PrivateKey(ReadOnlySpan source, Int32& bytesRead)
我在网上寻找答案,但我找不到任何有用的东西。 当我注释掉
rsa.ImportPkcs8PrivateKey(privateKeyBytes, out _)
时,它在生产中完美运行
public static string SignTool(string data, string privateKey)
{
using (var rsa = RSA.Create())
{
//byte[] privateKeyBytes = Convert.FromBase64String(privateKey);
rsa.ImportFromPem(Config.Config.private_key.ToCharArray());
/*
make sure that your private key is in the format of
-----BEGIN PRIVATE KEY-----
your private key goes here
-----END PRIVATE KEY-----
*/
var dataToSign = Encoding.UTF8.GetBytes(data);
var signature = rsa.SignData(dataToSign, HashAlgorithmName.SHA256, RSASignaturePadding.Pss);
return Convert.ToBase64String(signature);
}
}
我遇到了同样的问题(C#/.NetCore 6 和 7,Windows)。在我的本地开发电脑上,我的代码有效。在 azure 函数中,代码有效……但它在 webjob 中不起作用,它产生了相同的错误。这也是一个奇怪的错误,因为我的代码没有使用文件。您的代码也没有指定文件的使用。
我看到了这篇信息丰富的简短文章:https://dusted.codes/how-to-use-rsa-in-dotnet-rsacryptoserviceprovider-vs-rsacng-and-good-practise-patterns
基于此,我决定使用 RSACryptoServiceProvider 替代 RSA.Create(),它立即完美运行。希望它能帮助任何人。