Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify a signature with a public key provided in .pem File?

Tags:

c#

certificate

How can I verify a signature with a public key provided in .pem File?

I use the flowing code:

RSACryptoServiceProvider CrRsa;

var reader21 = File.OpenText(@"C:GTLpublicKey.pem");
var x = new PemReader(reader21);
var y = (RsaKeyParameters)x.ReadObject();

CrRsa = (RSACryptoServiceProvider)RSACryptoServiceProvider.Create();
RSAParameters pa = new RSAParameters();
pa.Modulus = y.Modulus.ToByteArray();
pa.Exponent = y.Exponent.ToByteArray();
CrRsa.ImportParameters(pa);

y returns null, results in an Error at pa.Modulus = y.Modulus.ToByteArray();

like image 271
Sreegth Avatar asked Dec 26 '22 20:12

Sreegth


2 Answers

RSACryptoServiceProvider RSAVerifier = new RSACryptoServiceProvider();

//Read public Key From Text File.

StreamReader PubKeyReader = File.OpenText(txtPublicKeyFile.Text);

string publicKey = PubKeyReader.ReadToEnd();

//Adding public key to RSACryptoServiceProvider object.

RSAVerifier.FromXmlString(publicKey);

//Reading the Signature to verify.

FileStream Signature = new FileStream(txtVerifySign.Text, FileMode.Open, FileAccess.Read);

BinaryReader SignatureReader = new BinaryReader(Signature);

byte[] SignatureData = SignatureReader.ReadBytes((int)Signature.Length);

//Reading the Signed File for Verification.

FileStream Verifyfile = new FileStream(txtVerifyFile.Text, FileMode.Open, FileAccess.Read);

BinaryReader VerifyFileReader = new BinaryReader(Verifyfile);

byte[] VerifyFileData = VerifyFileReader.ReadBytes((int)Verifyfile.Length);

//Comparing.

bool isValidsignature = RSAVerifier.VerifyData(VerifyFileData, "SHA1", SignatureData);

if (isValidsignature)

{

      Signature.Close();

      Verifyfile.Close();

}

else

{


    Signature.Close();

    Verifyfile.Close();

}
like image 132
Sreegth Avatar answered Apr 14 '23 16:04

Sreegth


I disagree with the proposed answer.

RSACryptoServiceProvider can't read a PEM file through "FromXMLString".

However, it gave me the idea to export the PEM file to XML.

I found this site that makes the online conversion

Then it worked perfectly!

like image 27
Emmanuel Larrieux Avatar answered Apr 14 '23 15:04

Emmanuel Larrieux