Python 3.6 compatibility: random bits & bcrypt

Switched from Sybren's RSA library to the new stdlib module 'secrets' to
generate secret tokens. This also means that the rsa library was demoted
to secondary requirement.
This commit is contained in:
2017-03-03 14:16:29 +01:00
parent 2e41c074b5
commit dcdcd99393
3 changed files with 18 additions and 9 deletions

View File

@@ -5,7 +5,6 @@ import typing
import bcrypt
import datetime
import rsa.randnum
from bson import tz_util
from flask import abort, Blueprint, current_app, jsonify, request
from pillar.api.utils.authentication import create_new_user_document
@@ -77,7 +76,12 @@ def generate_and_store_token(user_id, days=15, prefix=b''):
:return: the token document.
"""
random_bits = rsa.randnum.read_random_bits(256)
if not isinstance(prefix, bytes):
raise TypeError('prefix must be bytes, not %s' % type(prefix))
import secrets
random_bits = secrets.token_bytes(32)
# Use 'xy' as altargs to prevent + and / characters from appearing.
# We never have to b64decode the string anyway.

View File

@@ -4,7 +4,6 @@ import logging
import urllib.parse
import pymongo.errors
import rsa.randnum
import werkzeug.exceptions as wz_exceptions
from bson import ObjectId
from flask import current_app, g, Blueprint, request
@@ -150,13 +149,19 @@ def make_world_gettable(node):
node_id)
def create_short_code(node):
def create_short_code(node) -> str:
"""Generates a new 'short code' for the node."""
import secrets
length = current_app.config['SHORT_CODE_LENGTH']
bits = rsa.randnum.read_random_bits(32)
short_code = base64.b64encode(bits, altchars='xy').rstrip('=')
short_code = short_code[:length]
# Base64 encoding will expand it a bit, so we'll cut that off later.
# It's a good idea to start with enough bytes, though.
bits = secrets.token_bytes(length)
short_code = base64.b64encode(bits, altchars=b'xy').rstrip(b'=')
short_code = short_code[:length].decode('ascii')
return short_code