crypto.py
branchstable
changeset 4598 437867dde236
parent 4595 bb08a75832e6
child 5421 8167de96c523
equal deleted inserted replaced
4586:440e340c61fe 4598:437867dde236
       
     1 """Simple cryptographic routines, based on python-crypto.
       
     2 
       
     3 :organization: Logilab
       
     4 :copyright: 2009-2010 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2.
       
     5 :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
       
     6 :license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses
       
     7 """
       
     8 __docformat__ = "restructuredtext en"
       
     9 
       
    10 from pickle import dumps, loads
       
    11 from base64 import b64encode, b64decode
       
    12 
       
    13 from Crypto.Cipher import Blowfish
       
    14 
       
    15 
       
    16 _CYPHERERS = {}
       
    17 def _cypherer(seed):
       
    18     try:
       
    19         return _CYPHERERS[seed]
       
    20     except KeyError:
       
    21         _CYPHERERS[seed] = Blowfish.new(seed, Blowfish.MODE_ECB)
       
    22         return _CYPHERERS[seed]
       
    23 
       
    24 
       
    25 def encrypt(data, seed):
       
    26     string = dumps(data)
       
    27     string = string + '*' * (8 - len(string) % 8)
       
    28     string = b64encode(_cypherer(seed).encrypt(string))
       
    29     return unicode(string)
       
    30 
       
    31 
       
    32 def decrypt(string, seed):
       
    33     # pickle ignores trailing characters so we do not need to strip them off
       
    34     string = _cypherer(seed).decrypt(b64decode(string))
       
    35     return loads(string)