crypto.py
author Sylvain Thénault <sylvain.thenault@logilab.fr>
Fri, 12 Mar 2010 15:05:33 +0100
changeset 4897 e402e0b32075
parent 4595 bb08a75832e6
child 5421 8167de96c523
permissions -rw-r--r--
[web] start a new message system based on id of message stored in session's data instead of using __message as today, which is problematic (allow message injection). Also we can have html in messages. Removed the __createdpath hack used to escape those limitation. The old system should still work though (and will probably for a while, though we should progressivly move to the new system where it's possible). Cleanup request paramaters handling on the way.

"""Simple cryptographic routines, based on python-crypto.

:organization: Logilab
:copyright: 2009-2010 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2.
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses
"""
__docformat__ = "restructuredtext en"

from pickle import dumps, loads
from base64 import b64encode, b64decode

from Crypto.Cipher import Blowfish


_CYPHERERS = {}
def _cypherer(seed):
    try:
        return _CYPHERERS[seed]
    except KeyError:
        _CYPHERERS[seed] = Blowfish.new(seed, Blowfish.MODE_ECB)
        return _CYPHERERS[seed]


def encrypt(data, seed):
    string = dumps(data)
    string = string + '*' * (8 - len(string) % 8)
    string = b64encode(_cypherer(seed).encrypt(string))
    return unicode(string)


def decrypt(string, seed):
    # pickle ignores trailing characters so we do not need to strip them off
    string = _cypherer(seed).decrypt(b64decode(string))
    return loads(string)