security.py 1.01 KB
Newer Older
1 2 3 4 5 6 7
import os
from binascii import hexlify


__all__ = ['random', 'armored_random',
    'new_user_key', 'new_salt', 'new_secret']

Romain Bignon's avatar
Romain Bignon committed
8
SECURE = os.getenv('ASSNET_FAST_TEST') != '1'
9

10 11 12 13 14 15

def random(n):
    """
    Get random bytes.
    Try to use the best random source or fall back to os.urandom.
    """
16
    source = "/dev/random" if SECURE else "/dev/urandom"
17
    try:
18
        with open(source, "r") as randomfd:
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
            bs = b""
            while n > len(bs):
                bs += randomfd.read(n - len(bs))
            return bs
    except (OSError, IOError):
        return os.urandom(n)


def armored_random(n):
    """
    Get a random string with no special characters.
    n is the number of source bytes, not the final string length.
    """
    return hexlify(random(n))


def new_user_key():
    return armored_random(16)


def new_salt():
    return armored_random(42)


def new_secret():
    """
    Replacement for hexlify(paste.auth.cookie.new_secret())
    Must return a string of 128.
    """
    return armored_random(64)