yawPyCrypto : encrypt file in blocks
John Hunter
jdhunter at ace.bsd.uchicago.edu
Fri Aug 29 09:37:39 EDT 2003
>>>>> "John" == John Hunter <jdhunter at ace.bsd.uchicago.edu> writes:
John> Apparently, I am not handling the final bytes correctly.
John> The file size are listed below the code.
John> Any advice? Also, is this the best way to encrypt large
John> files? Is there a preferred block size?
Hmmm, I thought I had posted a follow up to this yesterday but it
didn't appear to come through. Apologies if you get a duplicate.
I discovered the source of this problem. I needed to write the
encrypted/decrypted stream one more time after the call to finish.
The following works
from yawPyCrypto.Cipher import DecryptCipher, EncryptCipher
from yawPyCrypto.Cipher import ZipDecryptCipher, ZipEncryptCipher
from yawPyCrypto.Constants import CIPHER_BLOWFISH, MODE_CBC
def encrypt(passwd, infile, outfile, blocksize=1024, enc=None):
"""
Encrypt the data in the file handle infile to the file handle
outfile in blocks of length blocksize
enc is a EncryptCipher instace. If None, default to
EncryptCipher(passwd, CIPHER_BLOWFISH, MODE_CBC)
"""
if enc is None:
enc = EncryptCipher(passwd, CIPHER_BLOWFISH, MODE_CBC)
while 1:
data = infile.read(blocksize)
if len(data)==0: break
enc.feed(data)
outfile.write(enc.data)
enc.finish()
outfile.write(enc.data)
infile.close()
outfile.close()
def decrypt(passwd, infile, outfile, blocksize=1024, dec=None):
"""
Decrypt the data in the file handle infile to the file handle
outfile in blocks of length blocksize
dec is a DecryptCipher instace. If None, default to
DecryptCipher(passwd)
"""
if dec is None:
dec = DecryptCipher(passwd)
while 1:
data = infile.read(blocksize)
if len(data)==0: break
dec.feed(data)
outfile.write(dec.data)
dec.finish()
outfile.write(dec.data)
infile.close()
outfile.close()
passwd = 'a really bad passwd'
infile = file('source.mp3', 'rb')
outfile = file('crypted.mp3.cr', 'wb')
encrypt(passwd, infile, outfile)
infile = file('crypted.mp3.cr', 'rb')
outfile = file('decrypted.mp3', 'wb')
decrypt(passwd, infile, outfile)
More information about the Python-list
mailing list