Generate 2FA secret code cryptographically install of using random number

This commit is contained in:
venusbb
2017-06-09 16:19:30 +01:00
parent 43aade9ab5
commit a0640bb803
2 changed files with 64 additions and 1 deletions

View File

@@ -3,7 +3,7 @@ from datetime import (datetime, timedelta)
from sqlalchemy import func
from app import db
from app.models import (User, VerifyCode)
from app import secrets
def _remove_values_for_keys_if_present(dict, keys):
for key in keys:
@@ -11,6 +11,13 @@ def _remove_values_for_keys_if_present(dict, keys):
def create_secret_code():
'''
L1 = []
for i in range(0, 5):
L1.append(secrets.randbelow(10)) #return cryptographically strong random number using secrets module
L2 = ''.join(map(str, L1))
return L2
'''
return ''.join(map(str, random.sample(range(9), 5)))

56
app/secrets.py Normal file
View File

@@ -0,0 +1,56 @@
__all__ = ['choice', 'randbelow', 'randbits', 'SystemRandom',
'token_bytes', 'token_hex', 'token_urlsafe',
'compare_digest',
]
import base64
import binascii
import os
from hmac import compare_digest
from random import SystemRandom
_sysrand = SystemRandom()
randbits = _sysrand.getrandbits
choice = _sysrand.choice
def randbelow(exclusive_upper_bound):
"""Return a random int in the range [0, n)."""
if exclusive_upper_bound <= 0:
raise ValueError("Upper bound must be positive.")
return _sysrand._randbelow(exclusive_upper_bound)
DEFAULT_ENTROPY = 32 # number of bytes to return by default
def token_bytes(nbytes=None):
"""Return a random byte string containing *nbytes* bytes.
If *nbytes* is ``None`` or not supplied, a reasonable
default is used.
>>> token_bytes(16) #doctest:+SKIP
b'\\xebr\\x17D*t\\xae\\xd4\\xe3S\\xb6\\xe2\\xebP1\\x8b'
"""
if nbytes is None:
nbytes = DEFAULT_ENTROPY
return os.urandom(nbytes)
def token_hex(nbytes=None):
"""Return a random text string, in hexadecimal.
The string has *nbytes* random bytes, each byte converted to two
hex digits. If *nbytes* is ``None`` or not supplied, a reasonable
default is used.
>>> token_hex(16) #doctest:+SKIP
'f9bf78b9a18ce6d46a0cd2b0b86df9da'
"""
return binascii.hexlify(token_bytes(nbytes)).decode('ascii')
def token_urlsafe(nbytes=None):
"""Return a random URL-safe text string, in Base64 encoding.
The string has *nbytes* random bytes. If *nbytes* is ``None``
or not supplied, a reasonable default is used.
>>> token_urlsafe(16) #doctest:+SKIP
'Drmhze6EPcv0fN_81Bj-nA'
"""
tok = token_bytes(nbytes)
return base64.urlsafe_b64encode(tok).rstrip(b'=').decode('ascii')