一直在兜圈子。
花了很长时间阅读和研究。我需要使用 X.509 证书对字符串进行签名。
以下方法应该有效但不起作用
Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates
Imports System.Text
Public Class CertificateSigner
Public Function SignStringWithCertificate(inputString As String, certificateFilePath As String, certificatePassword As String) As String
Try
' Load the certificate from file
Dim certificate As New X509Certificate2(certificateFilePath, certificatePassword)
' Get the private key from the certificate
Dim privateKey As AsymmetricAlgorithm = certificate.PrivateKey
' Create a new instance of the RSACryptoServiceProvider class
Dim rsaProvider As RSACryptoServiceProvider = CType(privateKey, RSACryptoServiceProvider)
' Convert the input string to bytes
Dim inputBytes As Byte() = Encoding.UTF8.GetBytes(inputString)
' Sign the data using the private key
Dim signatureBytes As Byte() = rsaProvider.SignData(inputBytes, CryptoConfig.MapNameToOID("SHA256"))
' Convert the signature to a base64-encoded string
Dim signatureBase64 As String = Convert.ToBase64String(signatureBytes)
Return signatureBase64
Catch ex As Exception
Debug.Print (ex.Message )
' Handle any exceptions here
Return Nothing
End Try
End Function
End Class
问题发生在
rsaProvider.SignData(inputBytes, CryptoConfig.MapNameToOID("SHA256"))
,异常给了我Invalid algorithm specified.
一切我读过的都说应该有效。
请问为什么会失败?
Vb.Net目标框架是4.6.1
您不能将 SHA256 算法与您的代码使用的旧版 CryptoAPI 1.0 一起使用。从 .NET Framework 4.6 开始,您可以(并且应该)使用 CAPI2 功能,包括 SHA256 算法。您必须更改获取私钥对象的方式。
X509Certificate2.PrivateKey
事实上已过时,不应再使用。使用 X509Certificate2.GetRSAPrivateKey 扩展方法使用 CAPI2 检索私钥。那么你的代码将如下所示(仅显示相关部分):
' Get the private key from the certificate
Dim privateKey As RSA = certificate.GetRSAPrivateKey()
' Convert the input string to bytes
Dim inputBytes As Byte() = Encoding.UTF8.GetBytes(inputString)
' Sign the data using the private key
Dim signatureBytes As Byte() = privateKey.SignData(inputBytes, "SHA256", RSASignaturePadding.Pkcs1)