Reputation: 139
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();
Upvotes: 4
Views: 13352
Reputation: 139
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();
}
Upvotes: 7
Reputation: 31
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!
Upvotes: 3
Reputation: 47945
Not sure but probably is the problem that you forgot a backsslash:
var reader21 = File.OpenText(@"C:\GTLpublicKey.pem");
// ^
Upvotes: 0