0

I am fairly new to python and pycrypto. I read many guides and manuals on pycrypto and I have come up with a small bit of code. I don't understand how to choose which files I want to encrypt. Is it supposed to be defined somewhere? My code:

import os, random, struct
from Crypto.Cipher import AES

def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):

if not out_filename:
    out_filename = in_filename + '.enc'

iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))
encryptor = AES.new(key, AES.MODE_CBC, iv)
filesize = os.path.getsize(in_filename)

with open(in_filename, 'rb') as infile:
    with open(out_filename, 'wb') as outfile:
        outfile.write(struct.pack('<Q', filesize))
        outfile.write(iv)

        while True:
            chunk = infile.read(chunksize)
            if len(chunk) == 0:
                break
            elif len(chunk) % 16 != 0:
                chunk += ' ' * (16 - len(chunk) % 16)

            outfile.write(encryptor.encrypt(chunk))

I just want to know how to choose which specific file to encrypt. I tried to write he file path in with open but that didn't seem to work.

  • The code you posted doesn't actually do anything on its own; it just defines a function named ``encrypt_file``. You pass the filename to be encrypted as the second parameter of this function when you call it. If you want to encrypt multiple files, you call the function multiple times (perhaps in a loop). – jasonharper Mar 09 '17 at 16:13
  • So I should define in_filename? like in_filename="C:/Users/foo/Desktop/passwords.txt"? –  Mar 09 '17 at 16:21
  • ``in_filename`` is what the parameter is named INSIDE the function. You can call it whatever you want outside the function - whatever the second value is within the call to ``encrypt_file( )`` becomes in_filename that is used. – jasonharper Mar 09 '17 at 16:26
  • Sorry, I am pretty new to this and a bit confused. So in the code it says out_filename = in_filename + '.enc'. SO if I define in_filename, shouldn't the code create another file called passwords.enc? –  Mar 09 '17 at 16:29
  • You DON'T define in_filename yourself - that name is an internal detail of the function. You could call ``encrypt_file("KEY", "passwords")``, and in_filename would become "passwords" (resulting in an output file named "passwords.enc", if you don't supply the optional third parameter to override that). You could call ``encrypt_file(myKey, myFilename)`` and it would come from the variable myFilename. You could call ``encrypt_file(input("Key: "), input("Filename: "))`` and it would come directly from user input. – jasonharper Mar 09 '17 at 16:35
  • Thank you. So I understand the filename part, but what about the key. Is it supposed to be any 32 bit string? –  Mar 09 '17 at 16:37
  • I'm not sure about the requirements of the key. You'd have to look at the documentation for the Crypto.Cipher.AES class to see what it wants. – jasonharper Mar 09 '17 at 16:40

0 Answers0