crypto.py 1.63 KB
Newer Older
1
# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
2
3
4
5
6
7
8
9
10
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of CubicWeb.
#
# CubicWeb is free software: you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 2.1 of the License, or (at your option)
# any later version.
#
11
# CubicWeb is distributed in the hope that it will be useful, but WITHOUT
12
13
14
15
16
17
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
18
"""Simple cryptographic routines, based on python-crypto."""
Sylvain Thénault's avatar
Sylvain Thénault committed
19

20
21

from base64 import b64encode, b64decode
Denis Laxalde's avatar
Denis Laxalde committed
22
import pickle
23

24
from Cryptodome.Cipher import Blowfish
25
26
27


_CYPHERERS = {}
Denis Laxalde's avatar
Denis Laxalde committed
28
29


30
def _cypherer(seed):
31
32
    if isinstance(seed, str):
        seed = seed.encode('utf-8')
33
34
35
36
37
38
39
40
    try:
        return _CYPHERERS[seed]
    except KeyError:
        _CYPHERERS[seed] = Blowfish.new(seed, Blowfish.MODE_ECB)
        return _CYPHERERS[seed]


def encrypt(data, seed):
41
    string = pickle.dumps(data)
42
    string = string + b'*' * (8 - len(string) % 8)
43
    string = b64encode(_cypherer(seed).encrypt(string))
44
    return string.decode('utf-8')
45
46
47


def decrypt(string, seed):
48
    string = string.encode('utf-8')
49
50
    # pickle ignores trailing characters so we do not need to strip them off
    string = _cypherer(seed).decrypt(b64decode(string))
51
    return pickle.loads(string)