Python read text file as binary? -
i trying build encryption program in python 2.7. read binary file , use key encrypt it. however, ran problem. files image files , executables read hex values. however, text files not using open(). if run
file=open("myfile.txt", "rb")
out=file.read()
it still comes out text. i'm on windows 7, not linux think may make difference. there way read binary file (including text files), not image , executable files?
take @ below code .also has many points you
from hashlib import md5 crypto.cipher import aes crypto import random def derive_key_and_iv(password, salt, key_length, iv_length): d = d_i = '' while len(d) < key_length + iv_length: d_i = md5(d_i + password + salt).digest() d += d_i return d[:key_length], d[key_length:key_length+iv_length] def encrypt(in_file, out_file, password, key_length=32): bs = aes.block_size salt = random.new().read(bs - len('salted__')) key, iv = derive_key_and_iv(password, salt, key_length, bs) cipher = aes.new(key, aes.mode_cbc, iv) out_file.write('salted__' + salt) finished = false while not finished: chunk = in_file.read(1024 * bs) if len(chunk) == 0 or len(chunk) % bs != 0: padding_length = (bs - len(chunk) % bs) or bs chunk += padding_length * chr(padding_length) finished = true out_file.write(cipher.encrypt(chunk)) def decrypt(in_file, out_file, password, key_length=32): bs = aes.block_size salt = in_file.read(bs)[len('salted__'):] key, iv = derive_key_and_iv(password, salt, key_length, bs) cipher = aes.new(key, aes.mode_cbc, iv) next_chunk = '' finished = false while not finished: chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1024 * bs)) if len(next_chunk) == 0: padding_length = ord(chunk[-1]) chunk = chunk[:-padding_length] finished = true out_file.write(chunk)
usage
with open(in_filename, 'rb') in_file, open(out_filename, 'wb') out_file: encrypt(in_file, out_file, password) open(in_filename, 'rb') in_file, open(out_filename, 'wb') out_file: decrypt(in_file, out_file, password)
Comments
Post a Comment