Verify signature for x509 certificate

I have:

  • x509 certificate (Base64);
  • String data
  • Signature of string data (Base64).

Can I verify the signature?

My code is:

bool valid = false; var signature = Convert.FromBase64String(base64Signature); var data = Encoding.UTF8.GetBytes(stringData); var x509 = new X509Certificate2(Convert.FromBase64String(certificate)); var dsa = x509.PublicKey.Key as DSACryptoServiceProvider; if (dsa!=null) valid = dsa.VerifySignature(data, signature); else { var rsa = x509.PublicKey.Key as RSACryptoServiceProvider; if (rsa!=null) valid = rsa.VerifyHash(data, ???, signature); } 

I do not know what I should use instead ???. Can I get a hash algorithm from a certificate?

+4
source share
1 answer

The sender of the original message can use any algorithm that he likes to sign with his message, using the private key corresponding to the certificate. Although you can get the OID of the algorithm used to sign the certificate from its SignatureAlgorithm property, nothing prevents the sender from using a different signature or hash algorithm.

According to the documentation , the only valid hashing algorithms for the RSA provider are SHA1 and MD5. Perhaps you should try VerifyHash with both algorithms and check which one succeeds. You can get the correct OID for each of them using the CryptoConfig.MapNameToOID method:

 string sha1Oid = CryptoConfig.MapNameToOID("SHA1"); string md5Oid = CryptoConfig.MapNameToOID("MD5"); bool sha1Valid = rsa.VerifyHash(data, sha1Oid, signature); bool md5Valid = rsa.VerifyHash(data, md5Oid, signature); valid = sha1Valid || md5Valid; 
+4
source

Source: https://habr.com/ru/post/1315911/


All Articles