public static string MD5Encryption(string stringToEncrypt, EncryptionKey encryptionKey) { byte[] sourceBytes; System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); // Step 1. We hash the passphrase using MD5 // We use the MD5 hash generator as the result is a 128 bit byte array // which is a valid length for the TripleDES encoder we use below MD5CryptoServiceProvider mcsp = new MD5CryptoServiceProvider(); byte[] TDESByte = mcsp.ComputeHash(UTF8.GetBytes(encryptionKey.GetCustomDescription())); // Step 2. Create a new TripleDESCryptoServiceProvider object TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider(); // Step 3. Setup the encoder TDESAlgorithm.Key = TDESByte; TDESAlgorithm.Mode = CipherMode.ECB; TDESAlgorithm.Padding = PaddingMode.PKCS7; // Step 4. Convert the input string to a byte[] byte[] dataToEncrypt = UTF8.GetBytes(stringToEncrypt); // Step 5. Attempt to encrypt the string try { ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor(); sourceBytes = Encryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length); } finally { // Clear the TripleDes and Hashprovider services of any sensitive information TDESAlgorithm.Clear(); mcsp.Clear(); } // Step 6. Return the encrypted string as a base64 encoded string return(Convert.ToBase64String(sourceBytes)); }
public static string AesDecryption(string base64StringToDecrypt, EncryptionKey encryptionKey) { using (AesCryptoServiceProvider acsp = GetProvider(Encoding.Default.GetBytes(encryptionKey.GetCustomDescription().MD5HexString()))) { byte[] rawBytes = Convert.FromBase64String(base64StringToDecrypt); ICryptoTransform ict = acsp.CreateDecryptor(); using (MemoryStream ms = new MemoryStream(rawBytes, 0, rawBytes.Length)) using (CryptoStream cs = new CryptoStream(ms, ict, CryptoStreamMode.Read)) return((new StreamReader(cs)).ReadToEnd()); } }
public static string AesEncryption(string stringToEncrypt, EncryptionKey encryptionKey) { using (AesCryptoServiceProvider acsp = GetProvider(Encoding.Default.GetBytes(encryptionKey.GetCustomDescription().MD5HexString()))) { byte[] sourceBytes = Encoding.ASCII.GetBytes(stringToEncrypt); ICryptoTransform ict = acsp.CreateEncryptor(); using (MemoryStream ms = new MemoryStream()) using (CryptoStream cs = new CryptoStream(ms, ict, CryptoStreamMode.Write)) { cs.Write(sourceBytes, 0, sourceBytes.Length); cs.FlushFinalBlock(); byte[] encryptedBytes = ms.ToArray(); /***** .ToArray() is important, don't mess with the buffer *****/ return(Convert.ToBase64String(encryptedBytes)); } } }