crypto.py
changeset 11057 0b59724cb3f2
parent 11052 058bb3dc685f
child 11058 23eb30449fe5
equal deleted inserted replaced
11052:058bb3dc685f 11057:0b59724cb3f2
     1 # copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
       
     2 # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
       
     3 #
       
     4 # This file is part of CubicWeb.
       
     5 #
       
     6 # CubicWeb is free software: you can redistribute it and/or modify it under the
       
     7 # terms of the GNU Lesser General Public License as published by the Free
       
     8 # Software Foundation, either version 2.1 of the License, or (at your option)
       
     9 # any later version.
       
    10 #
       
    11 # CubicWeb is distributed in the hope that it will be useful, but WITHOUT
       
    12 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
       
    13 # FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
       
    14 # details.
       
    15 #
       
    16 # You should have received a copy of the GNU Lesser General Public License along
       
    17 # with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
       
    18 """Simple cryptographic routines, based on python-crypto."""
       
    19 __docformat__ = "restructuredtext en"
       
    20 
       
    21 from base64 import b64encode, b64decode
       
    22 
       
    23 from six.moves import cPickle as pickle
       
    24 
       
    25 from Crypto.Cipher import Blowfish
       
    26 
       
    27 
       
    28 _CYPHERERS = {}
       
    29 def _cypherer(seed):
       
    30     try:
       
    31         return _CYPHERERS[seed]
       
    32     except KeyError:
       
    33         _CYPHERERS[seed] = Blowfish.new(seed, Blowfish.MODE_ECB)
       
    34         return _CYPHERERS[seed]
       
    35 
       
    36 
       
    37 def encrypt(data, seed):
       
    38     string = pickle.dumps(data)
       
    39     string = string + '*' * (8 - len(string) % 8)
       
    40     string = b64encode(_cypherer(seed).encrypt(string))
       
    41     return unicode(string)
       
    42 
       
    43 
       
    44 def decrypt(string, seed):
       
    45     # pickle ignores trailing characters so we do not need to strip them off
       
    46     string = _cypherer(seed).decrypt(b64decode(string))
       
    47     return pickle.loads(string)