Having worked with txt files, I'm learning about binary now. My code below works for a while then bombs out, can you point me towards a method or module to read binary data line by line? The crypto module requires a buffer (don't know how to create one of those) or a string.

from Crypto.Cipher import AES

USEFILE = 'picture.bmp'

class encryptData():
        def __init__(self, file):
            
            blockSize = 32
            self.file = file
            secretKey = os.urandom(blockSize) 
            self.dataFile = open(file, "rb")
            cipher = AES.new(secretKey, AES.MODE_CFB)
            if self.dataFile:
                newFile = self.dataFile.readlines()
                for lines in newFile:
                        print cipher.encrypt(lines)
                
                
            print secretKey
                

run = encryptData(USEFILE)

I'm looking to read a binary file and encrypt it. Many thx.

Dani AI

Generated

A few practical corrections and a safe pattern to follow.

Binary files should be processed as byte streams, not with line-oriented calls. 's use of readlines() can load the whole file into memory and behaves oddly on binary data; that often explains crashes on large files. As pointed out, ciphertext is arbitrary bytes and will not render nicely on a terminal — avoid printing encrypted data directly and write it to a binary output instead (or encode it with base64 for debugging).

A minimal, robust streaming pattern (keeps memory small, stores IV with the ciphertext):

import os
from Crypto.Cipher import AES

in_path = "picture.bmp"
out_path = in_path + ".enc"

key = os.urandom(32)        # 16/24/32 bytes accepted by AES
iv  = os.urandom(16)        # 16-byte IV for AES

cipher = AES.new(key, AES.MODE_CFB, iv)

with open(in_path, "rb") as fin, open(out_path, "wb") as fout:
    fout.write(iv)                     # store IV first
    while True:
        chunk = fin.read(64*1024)
        if not chunk:
            break
        fout.write(cipher.encrypt(chunk))

Notes and cautions: CFB is a streaming mode so no block padding is needed, but the IV must be random and never reused with the same key. The key must be protected or derived from a secure KDF; do not hard-code it. For real applications follow 's advice: prefer a vetted high-level API (authenticated modes like AES-GCM or libraries such as the modern cryptography package/Fernet) instead of piecing primitives together. For debugging, encode ciphertext (for example with base64) before printing, and inspect tracebacks for MemoryError, NameError (missing imports), or file I/O errors.

Recommended Answers

All 4 Replies

In line
print cipher.encrypt(lines)
are you sure all the characters are printable?

BTW, Python relies on indentations, please keep them constant.

In line
print cipher.encrypt(lines)
are you sure all the characters are printable?

BTW, Python relies on indentations, please keep them constant.

Sorry, but DaniWeb is starting to give me a lot of double posts lately. I am suspicious that it happen when my darn Virus program updates in the background!

In line
print cipher.encrypt(lines)
are you sure all the characters are printable?

BTW, Python relies on indentations, please keep them constant.

Looks like it couldn't print all the characters, this line worked without bombing out.

print base64.b16encode(cipher.encrypt(lines))

I wasn't aware of unprintable characters, thx!

This is a good exercise if you're just playing around with the code because you're trying to learn. But if you're actually planning to implement encryption in an application that needs security then you should follow a couple pieces of advise. The firs is that "If you're typing the letters A E S into your code, you're doing it wrong." The other advise comes from Nate Lawson at Root Labs. "Don't implement your own crypto. Instead use SSL for transport and GPG for data at rest. If your design doesn't seem to fit that model, rework it until it does. If you can't, then use a high-level crypto library like cryptlib, GPGME, or Keyczar."

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.