c# - AES pads byte array with \0 when decrypting -
whenever decrypt file end \0 in between each character (this text file) original fine, , decryption successful without errors.
when open file ; "hello" become "h\0e\0l\0..."
here decryption function: (i came fix of converting byte array utf8 manually removing nulls, not solution. )
public static void decryptfiletofile(string fromfile, string tofile, byte[] key) { byte[] encryptedfile = io.convertfiletobyte(fromfile); using (aes aesalg = aes.create()) { byte[] dataiv = encryptedfile.take(16).toarray(); //first 16 bytes iv byte[] encrypteddata = encryptedfile.skip(16).take(encryptedfile.length-16).toarray(); aesalg.key = key; using (var decryptor = aesalg.createdecryptor(key, dataiv)) { byte[] final = performcryptography(decryptor, encrypteddata); string result = system.text.encoding.utf8.getstring(final); result = result.replace("\0", string.empty); io.writestringtofile(result,tofile); } } } private static byte[] performcryptography(icryptotransform cryptotransform, byte[] data) { using (var memorystream = new memorystream()) { using (var cryptostream = new cryptostream(memorystream, cryptotransform, cryptostreammode.write)) { cryptostream.write(data, 0, data.length); cryptostream.flushfinalblock(); return memorystream.toarray(); } } }
to encrypt:
public static void encryptfiletofile(string fromfile, string tofile, byte[] key){ byte[] original = io.convertfiletobyte(fromfile); using (aes aesalg = aes.create()) { aesalg.generateiv(); aesalg.key = key; using (var encryptor = aesalg.createencryptor(key, aesalg.iv)) { byte[] encrypteddata = performcryptography(encryptor, original); byte[] final = combine(aesalg.iv,encrypteddata); io.writebytetofile(final, tofile); } } }
Comments
Post a Comment