c# - AESManaged returns different encrypted value for same key/iv combination -
i found this article online , implemented 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]; (var = 0; < numberchars; += 2) bytes[i / 2] = convert.tobyte(hex.substring(i, 2), 16); return bytes; } now question have is, here providing same iv , key (obviously testing, in production i'm changing iv each time encrypt), it's returning different encrypted bytes each time encrypt same input.
i looked posts , said output supposed same specific key/iv combination. missing 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 how i'm calling encrypt method
so after discussion, problem part of code not shown here. indeed, original code above gave same results , unit test should have passed (with additionally using sequenceequal on assertion). however, aes.keysize changed in code (by colleagues) after setting key, this:
aes.key = stringtobytearray("abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890"); aes.iv = stringtobytearray("00010001000000000000000000000000"); aes.keysize = 128; however, found out outputting used key after setting keysize property using
console.writeline("used key encryption: " + bitconverter.tostring(aes.key)); the key changes random key after modify keysize. that's why kept getting different results. sample outputs calling function with same input vector:
used key encryption: c7-35-58-42-3a-2a-79-de-0d-09-78-20-34-90-1f-ec
ciphertext: e4-aa-a3-3b-01-cf-f0-c1-07-9a-0b-73-3e-70-c9-8aused key encryption: 8a-95-e7-26-60-f9-ce-66-ba-a4-de-d2-fa-70-ac-de
ciphertext: c5-e7-d3-32-38-21-54-25-86-61-70-cb-94-46-a6-37used key encryption: a4-d7-01-8f-35-2b-7f-2d-e6-0a-a9-7f-95-42-71-d6
ciphertext: f1-b2-75-64-d1-90-75-32-0d-cb-d9-ae-11-ae-db-dd
the problem solved first setting keysize , setting key property itself.
Comments
Post a Comment