I found this article online and implemented a modified version of it.
public static byte[] Encrypt(byte[] input, byte[] iv) { var aes = new AesManaged(); aes.Key = StringToByteArray("abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890"); aes.IV = StringToByteArray("00010001000000000000000000000000"); aes.KeySize = 128; var encryptor = aes.CreateEncryptor(); using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { cs.Write(input, 0, input.Length); cs.Close(); } return ms.ToArray(); } } public static byte[] StringToByteArray(string hex) { var NumberChars = hex.Length; var bytes = new byte[NumberChars / 2]; for (var i = 0; i < NumberChars; i += 2) bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); return bytes; } Now the question I have is, here I am providing same IV and Key (obviously just for testing, in production I'm changing the IV each time I encrypt), but it's returning different encrypted bytes each time I encrypt the same input.
I looked up some posts and they said the output is supposed to be same for specific key/iv combination. Am I missing something here?
EDIT:
[TestMethod] public void Encryption_returns_same_value_for_same_key_and_iv() { const string input = "my input"; var bytes = Encoding.UTF32.GetBytes(input); var result = EncryptionManager.Encrypt(bytes, bytes); var result2 = EncryptionManager.Encrypt(bytes, bytes); Assert.AreEqual(result, result2); } This is how i'm calling the encrypt method
aes.Modeandaes.Paddingto the console to see what kind of mode of operation theAesManaged()class uses by default? Randomization / Padding might have happened.Encrypt()function.