我必须为一个网络服务签名。该服务使用OpenSSL MD5签名。我从OpenSSL私钥文件生成PEM:
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=...which与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();
}发布于 2014-06-22 17:25:08
您的OpenSSL输出是一个十六进制字符串:
openssl.exe dgst -md5 -hex -out signature.txt -sign privKey.pem textToSign.txt
^当您的C#输出在Base64中时:
return Convert.ToBase64String(signedData);
^将byte[]输出转换为十六进制字符串:
https://stackoverflow.com/questions/24353746
复制相似问题