In this example, we will learn at implementing the cryptography object in C# to encrypt and decrypt information, either passwords or connection strings and prevent unauthorised eyes from prying at your passwords.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
using System; using System.Security.Cryptography; using System.IO; using System.Text; public class Program { public static void Main() { // declaring key var key = "b14ca5898a4e4133bbce2ea2315a1916"; // encrypt parameters var input = string.Concat("https://myDomain.in/", "Encrypt.aspx?query=", EncryptString(key, string.Format("emailID={0}", "myemail@gmail.com"))); Console.WriteLine("Encrypted Input: " + input); // decrypt parameters var decrptedInput = DecryptString(key, input.Substring(input.IndexOf("=") + 1)); Console.WriteLine("Decrypted Input: " + decrptedInput); } public static string EncryptString(string key, string plainInput) { byte[] iv = new byte[16]; byte[] array; using (Aes aes = Aes.Create()) { aes.Key = Encoding.UTF8.GetBytes(key); aes.IV = iv; ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write)) { using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream)) { streamWriter.Write(plainInput); } array = memoryStream.ToArray(); } } } return Convert.ToBase64String(array); } public static string DecryptString(string key, string cipherText) { byte[] iv = new byte[16]; byte[] buffer = Convert.FromBase64String(cipherText); using (Aes aes = Aes.Create()) { aes.Key = Encoding.UTF8.GetBytes(key); aes.IV = iv; ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); using (MemoryStream memoryStream = new MemoryStream(buffer)) { using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read)) { using (StreamReader streamReader = new StreamReader((Stream)cryptoStream)) { return streamReader.ReadToEnd(); } } } } } } |