encrypting files + filestreams?

Lawrence D'Oliveiro ldo at geek-central.gen.new_zealand
Sat Aug 18 00:48:14 EDT 2007


In message <1187186797.579680.206820 at 19g2000hsx.googlegroups.com>, per9000
wrote:

>     crptz = AES.new("my-secret_passwd")

You're using ECB mode. Never use ECB mode. At a minimum, use CBC mode.

Also, another common thing is, don't use the actual password to encrypt the
entire file. Instead, randomly generate a "session key" to use for the
actual encryption, and only use the password to encrypt that.

> def encrypt2(cryptor, infile, outfile):
>     """enly encrypt a few bytes at a time"""
> 
>     size = 512
>     bytes = infile.read(size)
> 
>     seek = 0
>     interval = 97
>     ctr = 0
> 
>     while len(bytes) == size:
>         seek += size
>         if ctr % interval == 0:
>             print '\r%15d bytes completed' %  (seek),
>         ctr += 1
> 
>         outfile.write(cryptor.encrypt(bytes))
>         # change to this to decrypt
>         # outfile.write(cryptor.decrypt(bytes))
>         bytes = infile.read(size)
> 
>     if len(bytes) != 0:
>         bytes += "#" * (size - len(bytes))
>         outfile.write(cryptor.encrypt(bytes))
>         seek += len(bytes)

Finally, it is recommended that you also compute and encrypt a cryptographic
hash of the plaintext. That way, you can check that still matches after
decryption, to guard against tampering.




More information about the Python-list mailing list