How to verify signature loading PUBLIC KEY from a PEM file?

I publish this in the hope that he will save someone else in those hours that I lost on this really silly issue related to converting public key formats. If anyone sees a simpler solution or problem, let me know!

The eCommerce system that I use sends me some data along with the signature. They also give me the public key in .pem format. The .pem file looks like this:

----- BEGIN PUBLIC KEY ----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDe + hkicNP7ROHUssGNtHwiT2Ew HFrSk / qwrcq8v5metRtTTFPE / nmzSkRnTs3GMpi57rBdxBBJW5W9cpNyGUh0jNXc VrOSClpD5Ri2hER / GcNrxVRP7RlWOqB1C03q4QYmwjHZ + zlM4OUhCCAtSWflB4wC Ka1g88CjFwRw / PB9kwIDAQAB ----- END PUBLIC KEY -----

Here is the magic code to turn this into a "RSACryptoServiceProvider" that is capable of verifying the signature. Uses the BouncyCastle library, since .NET seems to (and horribly can't do this without any major headaches associated with certificate files):

RSACryptoServiceProvider thingee; using (var reader = File.OpenText(@"c:\pemfile.pem")) { var x = new PemReader(reader); var y = (RsaKeyParameters)x.ReadObject(); thingee = (RSACryptoServiceProvider)RSACryptoServiceProvider.Create(); var pa = new RSAParameters(); pa.Modulus = y.Modulus.ToByteArray(); pa.Exponent = y.Exponent.ToByteArray(); thingee.ImportParameters(pa); } 

And then the code to actually verify the signature:

 var signature = ... //reads from the packet sent by the eCommerce system var data = ... //reads from the packet sent by the eCommerce system var sha = new SHA1CryptoServiceProvider(); byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(data)); byte[] bSignature = Convert.FromBase64String(signature); ///Verify signature, FINALLY: var hasValidSig = thingee.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), bSignature); 
+4
source share
1 answer

Potential issue: using Encoding.ASCII.GetBytes(data) is almost certainly the wrong way to get a hash. This means that they can only send a hash that does not have any high bits.

If it is a “packet”, you should receive raw data from the packet as a byte array. If it is presented as text, it should be in some encoded form - for example. hex or base64. What does a hash look like?

+1
source

All Articles