// 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 TestAsymmetric { // encrypt: byte[] plain + byte[] keys -> byte[] cipher // decrypt: byte[] cipher + byte[] keys -> byte[] plain public static byte[] Encrypt(byte[] plain, byte[] keyblob) { RSACryptoServiceProvider alg = new RSACryptoServiceProvider(); alg.ImportCspBlob(keyblob); return alg.Encrypt(plain, false); } public static byte[] Decrypt(byte[] cipher, byte[] keyblob) { RSACryptoServiceProvider alg = new RSACryptoServiceProvider(); alg.ImportCspBlob(keyblob); return alg.Decrypt(cipher, false); } // 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); } // encrypt: string plain + byte[] keys -> Base64 string cipher // decrypt: Base64 string cipher + byte[] keys -> string plain public static string Encrypt(string plain, byte[] keyblob) { return Encode(Encrypt(Encoding.UTF8.GetBytes(plain), keyblob)); } public static string Decrypt(string cipher, byte[] keyblob) { return Encoding.UTF8.GetString(Decrypt(Decode(cipher), keyblob)); } // test private const string TEXT = "This is some random text to be used to test encryption."; private static void Test(string label, int bits) { Console.WriteLine(label + ":"); // generate keys RSACryptoServiceProvider alg = new RSACryptoServiceProvider { KeySize = bits }; byte[] keyblob = alg.ExportCspBlob(true); // real test Console.WriteLine(" " + TEXT); string cipher = Encrypt(TEXT, keyblob); Console.WriteLine(" " + cipher); string plain = Decrypt(cipher, keyblob); Console.WriteLine(" " + plain); } public static void Main(string[] args) { // CAPI implementations Test("RSA 2048 bit (CAPI)", 2048); Test("RSA 3072 bit (CAPI)", 3072); } } }