root / snf-cyclades-app / synnefo / db / aes_encrypt.py @ 30e0ed74
History | View | Annotate | Download (1.7 kB)
1 |
from binascii import b2a_base64, a2b_base64 |
---|---|
2 |
from Crypto.Cipher import AES |
3 |
from random import choice |
4 |
from string import letters, digits |
5 |
from synnefo.settings import ENCRYPTION_KEY |
6 |
|
7 |
|
8 |
DB_ENCRYPTED_FIELD_PREFIX = 'encrypted'
|
9 |
SALT_LEN = 8
|
10 |
|
11 |
|
12 |
def _pad_secret(secret, blocksize=32, padding='}'): |
13 |
if not len(secret) in (16, 24, 32): |
14 |
return secret + (blocksize - len(secret)) * padding |
15 |
return secret
|
16 |
|
17 |
|
18 |
def encrypt(s): |
19 |
obj = AES.new(_pad_secret(ENCRYPTION_KEY), AES.MODE_CFB) |
20 |
return obj.encrypt(s)
|
21 |
|
22 |
|
23 |
def decrypt(s): |
24 |
obj = AES.new(_pad_secret(ENCRYPTION_KEY), AES.MODE_CFB) |
25 |
return obj.decrypt(s)
|
26 |
|
27 |
|
28 |
def encrypt_db_charfield(plaintext): |
29 |
if plaintext == None: |
30 |
return plaintext
|
31 |
salt = "".join([choice(letters + digits) for i in xrange(SALT_LEN)]) |
32 |
|
33 |
plaintext = "%s%s" % (salt, plaintext)
|
34 |
# Encrypt and convert to binary
|
35 |
ciphertext = b2a_base64(encrypt(plaintext)) |
36 |
# Append prefix,salt and return encoded value
|
37 |
final = '%s:%s$%s' % (DB_ENCRYPTED_FIELD_PREFIX, salt, ciphertext)
|
38 |
return final.encode('utf8') |
39 |
|
40 |
|
41 |
def decrypt_db_charfield(ciphertext): |
42 |
if ciphertext == None: |
43 |
return ciphertext
|
44 |
has_prefix = ciphertext.startswith(DB_ENCRYPTED_FIELD_PREFIX + ':')
|
45 |
if not has_prefix: # Non-encoded value |
46 |
return ciphertext
|
47 |
else:
|
48 |
_, ciphertext = ciphertext.split(':')
|
49 |
|
50 |
pure_salt, encrypted = ciphertext.split('$')
|
51 |
|
52 |
plaintext = decrypt(a2b_base64(encrypted)) |
53 |
|
54 |
salt = plaintext[:SALT_LEN] |
55 |
plaintext = plaintext[SALT_LEN:] |
56 |
|
57 |
if salt != pure_salt:
|
58 |
# Can not decrtypt password
|
59 |
raise CorruptedPassword("Can not decrypt password. Check the key") |
60 |
else:
|
61 |
return plaintext
|
62 |
|
63 |
|
64 |
class CorruptedPassword(Exception): |
65 |
pass
|