public byte[] Encrypt(byte[] data) { // encrypt-then-MAC to protect against oracle attacks var ciphertext = Cipher.Encrypt(data); var mac = MAC.Calculate(ciphertext); var full_text = new byte[ciphertext.Length + mac.Length]; Array.Copy(ciphertext, 0, full_text, 0, ciphertext.Length); Array.Copy(mac, 0, full_text, ciphertext.Length, mac.Length); return(full_text); }
public byte[] Decrypt(byte[] data) { var ciphertext = new byte[data.Length - MAC.OutputLength]; var mac = new byte[MAC.OutputLength]; Array.Copy(data, 0, ciphertext, 0, ciphertext.Length); Array.Copy(data, ciphertext.Length, mac, 0, mac.Length); var calculated_mac = MAC.Calculate(ciphertext); if (!calculated_mac.SequenceEqual(mac)) { Log.Warn("Invalid MAC: Expected {0}, got {1} (len={2})", calculated_mac.ToUsefulString(), mac.ToUsefulString(), data.Length); return(new byte[0]); // corrupt MAC } return(Cipher.Decrypt(data)); }