I just tried this, and it works as expected. Thanks for this useful piece 
of code Niphlod. 
Just a bunch of 'gotchas', which I thought might help someone else trying 
this code:

   - I had existing data in the table, which was in plain text format. When 
   I introduced this code I encountered errors like "..Incorrect padding...". 
   Went ahead and commented out the filter* assignments, exported the plain 
   text data. Un-commented the filter* assignments, and imported the data. 
   - My data has long / integer / numeric fields, and I noticed errors in 
   the pad() method. Works well for non-numeric fields - primarily string 
   fields. 
   - Also removed NULL/None values from the dataset. 
   

On Wednesday, June 26, 2013 12:12:29 AM UTC+5:30, Niphlod wrote:
>
> sorry, cut&paste error.
>
>
>
> import gluon.contrib.aes as AES
> import threading 
> import os
> import base64
>
> def fast_urandom16(urandom=[], locker=threading.RLock()):
>     """
>     this is 4x faster than calling os.urandom(16) and prevents
>     the "too many files open" issue with concurrent access to os.urandom()
>     """
>     try:
>         return urandom.pop()
>     except IndexError:
>         try:
>             locker.acquire()
>             ur = os.urandom(16 * 1024)
>             urandom += [ur[i:i + 16] for i in xrange(16, 1024 * 16, 16)]
>             return ur[0:16]
>         finally:
>             locker.release()
>             
> def pad(s, n=32, padchar=' '):
>     return s + (32 - len(s) % 32) * padchar
>
> def AES_new(key, IV=None):
>     """ Returns an AES cipher object and random IV if None specified """
>     if IV is None:
>         IV = fast_urandom16()
>
>     return AES.new(key, AES.MODE_CBC, IV), IV
>
> def w2p_encrypt(data):
>     key = 'asdsaddasdasdas'
>     key = pad(key[:32])
>     cipher, IV = AES_new(key)
>     encrypted_data = IV + cipher.encrypt(pad(data))
>     return base64.urlsafe_b64encode(encrypted_data)
>
> def w2p_decrypt(data):
>     key = 'asdsaddasdasdas'
>     key = pad(key[:32])
>     data = base64.urlsafe_b64decode(data)
>     IV, data = data[:16], data[16:]
>     cipher, _ = AES_new(key, IV=IV)
>     data = cipher.decrypt(data)
>     data = data.rstrip(' ')
>     return data
>
> db.define_table('t_test',
>                 Field('f_field')
>                 )
>
> db.t_test.f_field.filter_in = lambda value : w2p_encrypt(value)
> db.t_test.f_field.filter_out = lambda value : w2p_decrypt(value)
>
>
>

-- 
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
--- 
You received this message because you are subscribed to the Google Groups 
"web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to web2py+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to