Omar Kh

Omar Kh

  • NA
  • 301
  • 21.6k

How to Sign & verify digital signature in C#

Sep 29 2022 10:14 AM

Im working on api project that requires Signing Verifying Digital signature

below the signing code

 public static string SignJSONMessage(string messageToSign,string certificateSerialNumber){

RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider();
rsaCryptoServiceProvider.FromXmlString(GetCertificates(certificateSerialNumber).PrivateKey.ToXmlString(true));
RSACryptoServiceProvider.UseMachineKeyStore = true;
rsaCryptoServiceProvider.ExportParameters(false);
rsaCryptoServiceProvider.KeySize = 2048;
return Convert.ToBase64String(rsaCryptoServiceProvider.SignData(Encoding.Unicode.GetBytes(messageToSign),
CryptoConfig.MapNameToOID("SHA256")));}

,  verifying 

 public static bool VerifyJSONMessage(string originalMessage, string signedMessage, string certificateSerialNumber)
{
RSACryptoServiceProvider rsaCryptoServiceProvider = (RSACryptoServiceProvider)GetCertificates(certificateSerialNumber).PublicKey.Key;RSACryptoServiceProvider.UseMachineKeyStore = true;
rsaCryptoServiceProvider.ExportParameters(false);
rsaCryptoServiceProvider.KeySize = 2048;
byte[] Signature;
try{
Signature = Convert.FromBase64String(SignedMessage);   
}
catch{return false;}
return rsaCryptoServiceProvider.VerifyData(Encoding.Unicode.GetBytes(originalMessage), CryptoConfig.MapNameToOID("SHA256"), Signature);}

there is no problem with the GetCertificates() method its woirking 

every time i check the verify it returns false!

,here's the code

string b_body = @"{""BilrCatCode"":1}";   
        var signature = SignJSONMessage(b_body, "Cert Serial Number");
bool x = VerifyJSONMessage(b_body, signature, "Cert Serial Number");

can any one help on this 

Thanks in advanced