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();
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);
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();
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.
}