C#使用RSA签名和验证签名。编码问题
我的问题与2011年的问题非常相似。然而,当我比较签名数据和原始消息时,我也会得到false。请指出我的错误 代码: 签字方式:C#使用RSA签名和验证签名。编码问题,c#,encoding,rsa,signing,C#,Encoding,Rsa,Signing,我的问题与2011年的问题非常相似。然而,当我比较签名数据和原始消息时,我也会得到false。请指出我的错误 代码: 签字方式: public static string SignData(string message, RSAParameters privateKey) { ASCIIEncoding byteConverter = new ASCIIEncoding(); byte[] signedBytes; using (va
public static string SignData(string message, RSAParameters privateKey)
{
ASCIIEncoding byteConverter = new ASCIIEncoding();
byte[] signedBytes;
using (var rsa = new RSACryptoServiceProvider())
{
// Write the message to a byte array using ASCII as the encoding.
byte[] originalData = byteConverter.GetBytes(message);
try
{
// Import the private key used for signing the message
rsa.ImportParameters(privateKey);
// Sign the data, using SHA512 as the hashing algorithm
signedBytes = rsa.SignData(originalData, CryptoConfig.MapNameToOID("SHA512"));
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
// Set the keycontainer to be cleared when rsa is garbage collected.
rsa.PersistKeyInCsp = false;
}
}
// Convert the byte array back to a string message
return byteConverter.GetString(signedBytes);
}
验证方法:
public static bool VerifyData(string originalMessage, string signedMessage, RSAParameters publicKey)
{
bool success = false;
using (var rsa = new RSACryptoServiceProvider())
{
ASCIIEncoding byteConverter = new ASCIIEncoding();
byte[] bytesToVerify = byteConverter.GetBytes(originalMessage);
byte[] signedBytes = byteConverter.GetBytes(signedMessage);
try
{
rsa.ImportParameters(publicKey);
success = rsa.VerifyData(bytesToVerify, CryptoConfig.MapNameToOID("SHA512"), signedBytes);
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
return success;
}
基本上,问题在于字符串到字节[]的编码。我在Asciencoding和UTF8编码中遇到了同样的问题
提前谢谢你 您不能对编码的消息使用
ascienceoding
,因为它包含的字节是无效的ASCII字符。存储编码消息的典型方式是使用base64字符串
在SignData
中,使用以下命令将字节数组编码为字符串:
return Convert.ToBase64String(signedBytes);
在VerifyData
中,使用以下命令将字符串解码回同一字节数组:
byte[] signedBytes = Convert.FromBase64String(signedMessage);
谢谢你的及时回复!但是,当我对消息“2017-04-10T09:37:35.351Z”使用FromBase64String时,会得到“System.FormatException:'输入不是有效的Base-64字符串,因为它包含非Base 64字符、两个以上的填充字符或填充字符中的非法字符”。在验证之前,字符串是否发生了任何变化?我用上面的两个改动运行了你发布的代码,它成功了。你说得对!我的缺点是,我还试图在签名之前执行原始数据的字符串到Base64字符串。
byte[] signedBytes = Convert.FromBase64String(signedMessage);