encrypt and descrypt a created file

Tim Chase python.list at tim.thechases.com
Sat Dec 13 17:12:41 CET 2008


> open(str(os.sep).join([
>     os.getcwd(),
>     'applications',
>     request.application,
>     'databases',
>     table+'.csv']),'w').write(str(db(db[table].id).select ())) 
>  
>  
> How can i encrypt and descrypt the created file above??

Well, as I was recently admonished (and have come to love), the 
first recommendation is to use the "csv" module for writing CSV 
files.  It deals with oddities like quotation-escaping, and a 
bunch of other details.

However, you want some sort of encryption/decryption method, but 
you don't specify what type.  You can do something simple like

   def encrypt(s):
     return s.encode('rot13')
   def decrypt(s):
     return s.decode('rot13')
   f = open(filename, 'wb')
   f.write(encrypt(content))
   f.close()
   f = open(filename, 'r')
   content = decrypt(f.read())
   f.close()

It's not very good encryption though ;-)  For better encryption 
see [1] & [2] for the pycrypto module.  It's been a while since 
I've done anything using this module, but the docs are available 
for it and the basic premise is the same (encrypt the content 
before writing, decrypt the content upon reading).  It would help 
to read up on crypto best-practices about storing key-files, 
password-management, etc.

-tkc


[1]
http://www.pycrypto.org

[2]
http://www.amk.ca/python/code/crypto.html






More information about the Python-list mailing list