encrypting files + filestreams?
Larry Bates
larry.bates at websafe.com
Wed Aug 15 14:58:34 EDT 2007
per9000 wrote:
> Hi python people,
>
> I am trying to figure out the best way to encrypt files in python.
>
> I've build a small script (see below) that encrypts the ubuntu 7.04
> iso file in 2 minutes (I like python :) ).
>
> But I have some thoughts about it. By pure luck (?) this file happened
> to be N*512 bytes long so I do not have to add crap at the end - but
> on files of the size N*512 + M (M != 521) I will add some crap to make
> it fit in the algorithm. When I later decrypt I will have the stuff I
> do not want. How do people solve this? (By writing the number of
> relevant bytes in readable text in the beginning of the file?)
>
> Also I wonder if this can be solved with filestreams (Are there
> streams in python? The only python file streams I found in the evil
> search engine was stuff in other forums.)
>
>
> Other comments are of course also welcome,
> Per
>
>
> # crypto_hardcoded.py starts here
>
> from Crypto.Cipher import AES
>
> 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)
>
> print '\r%15d bytes completed' % (seek)
>
> if __name__ == "__main__":
> crptz = AES.new("my-secret_passwd")
> ifile = file('/tmp/ubuntu-7.04-desktop-i386.iso','r')
> ofile = file('/tmp/ubuntu-7.04-desktop-i386.iso.out','w')
>
> encrypt2(crptz, ifile, ofile)
> ifile.close()
> ofile.close()
>
> # crypto_hardcoded.py ends here
>
Padding and keeping information in a header is how I solved the problem.
-Larry
More information about the Python-list
mailing list