<NME> cryptutils.py
<BEF> # coding: utf-8
from Crypto.Cipher import AES
import base64
import random
import string
from modoboa.lib import parameters


def random_key(l=16):
    """Generate a random key

    :param integer l: the key's length
    :return: a string
    """
    char_set = string.digits + string.letters + string.punctuation
    return ''.join(random.sample(char_set * l, l))


def encrypt(clear):


def _get_fernet():
    """Create a Fernet instance."""
    secret_key = base64.urlsafe_b64encode(smart_bytes(settings.SECRET_KEY[:32]))
    return Fernet(secret_key)


def encrypt(clear_value):
    """Encrypt a value using secret_key."""
    return smart_text(_get_fernet().encrypt(smart_bytes(clear_value)))


def decrypt(encrypted_value):
    """Decrypt a value using secret_key."""
    return smart_text(_get_fernet().decrypt(smart_bytes(encrypted_value)))


def get_password(request):
    """
    Retrieve and decrypt the users password from session storage.

    This is used by modoboa-webmail to allow the user to send/receive e-mails
    without having to ask the user for a password on each connection to the
    postfix/dovecot server.
    """
    try:
        return decrypt(request.session["password"])
    except KeyError:
        return None

<MSG> Make sure key has the required size.

see #867

<DFF> @@ -1,19 +1,26 @@
 # coding: utf-8
-from Crypto.Cipher import AES
+"""Crypto related utilities."""
+
 import base64
 import random
 import string
+
+from Crypto.Cipher import AES
+
 from modoboa.lib import parameters
 
 
 def random_key(l=16):
-    """Generate a random key
+    """Generate a random key.
 
     :param integer l: the key's length
     :return: a string
     """
-    char_set = string.digits + string.letters + string.punctuation
-    return ''.join(random.sample(char_set * l, l))
+    population = string.digits + string.letters + string.punctuation
+    while True:
+        key = "".join(random.sample(population * l, l))
+        if len(key) == l:
+            return key
 
 
 def encrypt(clear):

Make sure key has the required size.