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();
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();
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With