How to digitally sign a string

The first step is to create a pair of key(pulic/private):

RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
string publicKey = RSA.ToXmlString(false);
string privateKey = RSA.ToXmlString(true);
Private key is required to sign the string. Public key is required to verify if the sign is valid or not.

Sequence required to create a sign is:

  • select a private key

  • select an HASH algorithm to create one starting from the string to sign (you’ll sign the hash, not the string)

  • create a sign starting from the hash

As shown bellow:

RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(RSA);
SHA1Managed SHhash = new SHA1Managed();
byte[] SignedHashValue = RSAFormatter.CreateSignature( SHhash.ComputeHash(new UnicodeEncoding().GetBytes(stringToBeSigned)));
string signature = System.Convert.ToBase64String(SignedHashValue);
Sequence of operations needed to verify a signature is instead:

  • select the proper public key

  • select the HASH algorithm to create one starting from the string to be verified

  • veirfy the sign 

as shown below:

RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(RSA);
SHA1Managed SHhash = new SHA1Managed();
if (RSADeformatter.VerifySignature(
 SHhash.ComputeHash(new UnicodeEncoding().GetBytes(stringToBeVerified)),
 /// The signature is valid.
 /// The signature is not valid.

Skip to main content