I reviewed many forums and examples, but none helped me. I need verify signature from any webservice. I have test.crt file with public key for verify.
static bool Verify(string text, string signature)
{
X509Certificate2 cert = new X509Certificate2(
HttpContext.Current.Server.MapPath("test-server.cert"));
RSACryptoServiceProvider csp = (RSACryptoServiceProvider) cert.PublicKey.Key;
// Hash the data
SHA1Managed sha1 = new SHA1Managed();
UnicodeEncoding encoding = new UnicodeEncoding();
byte[] data = encoding.GetBytes(text);
byte[] sign = Convert.FromBase64String(signature);
byte[] hash = sha1.ComputeHash(data);
return csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), sign);
}
But result is always false :(
I have an OpenSSL example:
openssl base64 -d -in signature -out signature.bin
openssl dgst -sha1 -verify test-server.pub -signature signature.bin from_gateway
I suspect the use UnicodeEncoding could be the reason for failures. As demonstrated below the bytes of ASCIIEncoding and UnicodeEncoding are not same for the reason ASCII is a 8bit encoding and in Windows Unicode encoding is 16bit wide. In your other question Can not get signature you've used the ASCIIEncoding. So assuming signature is computed on the ASCIIEncoding bytes of the text/string and verify using UnicodeEncoding obviously will not match.
string text = "Hello";
Console.WriteLine("ASCIIEncoding bytes length: {0}", new ASCIIEncoding().GetBytes(text).Length);
Console.WriteLine("UnicodeEncoding bytes length: {0}", new UnicodeEncoding().GetBytes(text).Length);
Outputs
ASCIIEncoding bytes length: 5
UnicodeEncoding bytes length: 10