How to digitally sign a string

September 03, 2007 - 1 minute read

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

<PRE class=code>RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
string publicKey = RSA.ToXmlString(false);
string privateKey = RSA.ToXmlString(true); </PRE>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:

<PRE class=code>RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.FromXmlString(privateKey);
RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(RSA);
RSAFormatter.SetHashAlgorithm(“SHA1”);
SHA1Managed SHhash = new SHA1Managed();
byte[] SignedHashValue = RSAFormatter.CreateSignature( SHhash.ComputeHash(new UnicodeEncoding().GetBytes(stringToBeSigned)));
string signature = System.Convert.ToBase64String(SignedHashValue); </PRE>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:

<PRE class=code>RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.FromXmlString(publicKey);
RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(RSA);
RSADeformatter.SetHashAlgorithm(“SHA1”);
SHA1Managed SHhash = new SHA1Managed();
if (RSADeformatter.VerifySignature(
 SHhash.ComputeHash(new UnicodeEncoding().GetBytes(stringToBeVerified)),
 System.Convert.FromBase64String(signature))
 )
 {
 /// The signature is valid.
 }
else
 {
 /// The signature is not valid.
 } </PRE>

Tags: ,

Updated: