3

I was trying to build an encryption program in python 2.7. It would read the binary from a file and then use a key to encrypt it. However, I quickly ran into a problem. Files like image files and executables read as hex values. However, text files do not using open(). Even if i run

file=open("myfile.txt", "rb")

out=file.read()

it still comes out as just text. I'm on windows 7, not linux which i think may make a difference. Is there any way i could read the binary from ANY file (including text files), not just image and executable files?

3 Answers 3

3

Even when reading a file with the 'rb' flag, if your file has the byte '\x41' it will be printed as the letter 'A' in the console. If you want the hex values, encode the file content as hex, which means:

content = open('text.txt', 'rb').read()
# Since python 3.5:
hex = content.hex()
# else:
hex = content.encode('hex')
Sign up to request clarification or add additional context in comments.

2 Comments

Python 3.7.2: AttributeError: 'bytes' object has no attribute 'encode'
content.hex() should do it.
1

Take a look at below code .also it has many points for you

from hashlib import md5
from Crypto.Cipher import AES
from 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') as in_file, open(out_filename, 'wb') as out_file:
    encrypt(in_file, out_file, password)
with open(in_filename, 'rb') as in_file, open(out_filename, 'wb') as out_file:
    decrypt(in_file, out_file, password)

4 Comments

Yes but why doesn't that seem to work for text files? Like if I print the output it still prints as text
You seem like an experienced user. Why are you using stack snippets for code that is not runnable in the Browser? Please remove the stack snippet hints.
Correct command for read text files is like f = open('workfile.txt', 'r') but I didn't see your encrypt function .
Yes but i want to read the binary from the text file, like a hex editor, not the actual text.
1

Your binary file is coming out looking like text because the file is being treated like it is encoded in an 8 bit encoding (ASCII or Latin-1, etc). Also, in Python 2, bytes and (text) characters are used interchangeably... i.e. a string is just an array of ASCII bytes.

You should search the differences between python 2 and 3 text encoding and you will quickly see why anomalies such as you are encountering can develop. Most of the Python 2 version encryption modules use the python byte strings.

Your "binary" non-text files are not really being treated any differently from the text ones; they just don't map to an intelligible coding that you recognize, whereas the text ones do.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.