// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Security.Cryptography; using System.Text; namespace Encrypt { public class TestSigning { // sign: byte[] + byte[] keys -> byte[] // verify: byte[] + byte[] signature + byte[] keys -> bool public static byte[] Sign(byte[] content, byte[] keyblob, HashAlgorithm ha) { RSACryptoServiceProvider alg = new RSACryptoServiceProvider(); alg.ImportCspBlob(keyblob); return alg.SignData(content, ha); } public static bool Verify(byte[] content, byte[] signature, byte[] keyblob, HashAlgorithm ha) { RSACryptoServiceProvider alg = new RSACryptoServiceProvider(); alg.ImportCspBlob(keyblob); return alg.VerifyData(content, ha, signature); } // Base64 encode: byte[] -> string // Base64 decode: string -> byte[] private static string Encode(byte[] b) { return Convert.ToBase64String(b); } private static byte[] Decode(string s) { return Convert.FromBase64String(s); } // sign: string + byte[] keys -> Base64 string // verify: string + Base64 string signature + byte[] keys -> bool public static string Sign(string content, byte[] keyblob, HashAlgorithm ha) { return Encode(Sign(Encoding.UTF8.GetBytes(content), keyblob, ha)); } public static bool Verify(string content, string signature, byte[] keyblob, HashAlgorithm ha) { return Verify(Encoding.UTF8.GetBytes(content), Decode(signature), keyblob, ha); } // test private const string TEXT = "This is some random text to be used to test encryption."; private static void Test(string label, int bits, HashAlgorithm ha) { Console.WriteLine(label + ":"); // generate keys RSACryptoServiceProvider alg = new RSACryptoServiceProvider { KeySize = bits }; byte[] keyblob = alg.ExportCspBlob(true); // real test Console.WriteLine(" " + TEXT); string sig = Sign(TEXT, keyblob, ha); Console.WriteLine(" " + sig); bool ok = Verify(TEXT, sig, keyblob, ha); Console.WriteLine(" " + ok); bool ok2 = Verify(TEXT + "X", sig, keyblob, ha); Console.WriteLine(" " + ok2); } public static void Main(string[] args) { Test("SHA-1 160 bit with RSA 3072 bit", 3072, new SHA1CryptoServiceProvider()); Test("SHA-2 256 bit with RSA 3072 bit", 3072, new SHA256CryptoServiceProvider()); Test("SHA-2 512 bit with RSA 3072 bit", 3072, new SHA512CryptoServiceProvider()); } } }