. net MD5签名与OpenSSL MD5签名不匹配
本文关键字:MD5 不匹配 OpenSSL net | 更新日期: 2023-09-27 18:09:53
我必须为web服务签名消息。该服务使用OpenSSL MD5签名。我从PEM私钥文件生成OpenSSL:
openssl.exe dgst -md5 -hex -out signature.txt -sign privKey.pem textToSign.txt
生成以下签名:
7078388bd081d4b805feb020ab47352320919e4638e36b59d66a684c9bb12a745aaf172e4da2686c3e3750bf627c980a19700f6d8bbd0b62d8714a965a34be2e9f4147ac054c4af1050cdcebd9b475f0ef28e520681b0d67104b8e633ee592bb3ec2c517fb8cf7b13bd86424f00c89518e063d55e7922adab7cf607c85920862
我想在我的代码中实现这一点。我的实际代码是这样的(pfx文件中的私钥与pem文件中的私钥相同):
private static string Sign(string stringToSign)
{
X509Certificate2 cert = new X509Certificate2("keys.pfx", "", X509KeyStorageFlags.Exportable);
byte[] data = Encoding.UTF8.GetBytes(stringToSign);
byte[] signedData;
using (MD5 hasher = MD5.Create())
using (RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey)
{
signedData = rsa.SignData(data, hasher);
}
return Convert.ToBase64String(signedData);
}
这段代码产生了以下签名…
cHg4i9CB1LgF/rAgq0c1IyCRnkY442tZ1mpoTJuxKnRarxcuTaJobD43UL9ifJgKGXAPbYu9C2LYcUqWWjS+Lp9BR6wFTErxBQzc69m0dfDvKOUgaBsNZxBLjmM+5ZK7PsLFF/uM97E72GQk8AyJUY4GPVXnkirat89gfIWSCGI=
…它与OpenSLL不匹配。我应该怎么做才能匹配OpenSSL ?我也尝试使用OpenSSL。. NET,但是我没有找到任何签名的资源/教程。
解决正确的代码是:
private static string Sign(string stringToSign)
{
X509Certificate2 cert = new X509Certificate2("#02299991.pfx", "#02299991", X509KeyStorageFlags.Exportable);
byte[] data = Encoding.UTF8.GetBytes(stringToSign);
byte[] signedData;
using (MD5 hasher = MD5.Create())
using (RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey)
{
signedData = rsa.SignData(data, hasher);
}
return ByteArrayToString(signedData); //Convert.ToBase64String(signedData);
}
public static string ByteArrayToString(byte[] signedBytes)
{
StringBuilder hex = new StringBuilder(signedBytes.Length * 2);
foreach (byte b in signedBytes)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
您的OpenSSL输出是一个十六进制字符串:
openssl.exe dgst -md5 -hex -out signature.txt -sign privKey.pem textToSign.txt
^
当你的c#输出是Base64时:
return Convert.ToBase64String(signedData);
^
将byte[]
输出转换为十六进制字符串:
- 如何将字节数组转换为十六进制字符串,反之亦然?