我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用secrets.token_bytes()。
def hash_password(password: str, salt: Optional[bytes] = None) -> HashAndSalt: pepper = b'alchemists discovered that gold came from earth air fire and water' salt = salt or secrets.token_bytes(16) salted_pass = salt + password.encode('utf-8') return hashlib.pbkdf2_hmac('sha512', salted_pass, pepper, 100000), salt
def check_credentials(): user = request.forms.get('user', '') password = request.forms.get('password', '') if not pubsub.check_user(user, password): return show_main_page() token = secrets.token_bytes(32) logged_in_users.setdefault(token, user) response.set_cookie('token', token, max_age=60, secret=secret) return show_main_page(user)
def token_bytes(self, n): return urandom(n)
def mask(data, mask_key=None): """Mask data. data: raw data mask_key: reuse mask key""" if not mask_key: mask_key = secrets.token_bytes(4) new = [] for i, d in enumerate(data): new.append(struct.pack('>B', d ^ mask_key[i % 4])) new_data = b''.join(new) return new_data, mask_key
def _generate_split_token(): selector = base64.urlsafe_b64encode(secrets.token_bytes(SELECTOR_TOKEN_LENGTH)) verifier = base64.urlsafe_b64encode(secrets.token_bytes(SELECTOR_TOKEN_LENGTH+6)) return selector, verifier
def generate_csrf_token(user_id=None, user_last_login=None): """Generate csrf token from user id and user last login, or a random token if not logged in. :param user_id: Int. User id. :param user_last_login: Datetime. Last login datetime. :return: String. Token. """ if user_id and user_last_login: message = bytearray('{0}|{1}'.format(user_id, str(user_last_login)), 'utf-8') else: message = secrets.token_bytes(24) secret = bytearray(settings.SECRET_KEY, 'utf-8') return hmac.new(secret, msg=message, digestmod=hashlib.sha256).hexdigest()
def generate_token(cls): return token_bytes(64)
def create_test_file(self) -> (typing.IO, bytes): import io import secrets file_contents = secrets.token_bytes(512) test_file: typing.IO = io.BytesIO(file_contents) return test_file, file_contents
def create_short_code(node) -> str: """Generates a new 'short code' for the node.""" import secrets length = current_app.config['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
def generate_and_store_token(user_id, days=15, prefix=b'') -> dict: """Generates token based on random bits. NOTE: the returned document includes the plain-text token. DO NOT STORE OR LOG THIS unless there is a good reason to. :param user_id: ObjectId of the owning user. :param days: token will expire in this many days. :param prefix: the token will be prefixed by these bytes, for easy identification. :return: the token document with the token in plain text as well as hashed. """ 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. token_bytes = prefix + base64.b64encode(random_bits, altchars=b'xy').strip(b'=') token = token_bytes.decode('ascii') token_expiry = datetime.datetime.now(tz=tz_util.utc) + datetime.timedelta(days=days) token_data = store_token(user_id, token, token_expiry) # Include the token in the returned document so that it can be stored client-side, # in configuration, etc. token_data['token'] = token return token_data
def main(): parser = ArgumentParser(description='Generate a secret key.') parser.add_argument('-l', '--length', type=int, default=32, help='Length of secret key in bytes.') group = parser.add_mutually_exclusive_group(required=False) group.add_argument('-x', '--hex', action='store_true', help='Convert secret key to hexadecimal.') group.add_argument('-a', '--alphanum', action='store_true', help='Generate alphanumeric keys only.') A = parser.parse_args() if A.alphanum: alphabet = string.ascii_letters + string.digits print(''.join(choice(alphabet) for i in range(A.length))) elif A.hex: print(token_hex(A.length)) else: print(token_bytes(A.length)) #end if #end def
def setup_totp(request): if twofa.models.TOTPDevice.objects.active_for_user(request.user).exists(): messages.error(request, _('You may not have multiple Google Authenticators attached to your account.')) return redirect('twofa:list') setup_signer = TimestampSigner('twofa.views.setup_totp:{}'.format(request.user.pk)) if request.method == 'POST' and 'secret' in request.POST: try: b32_secret = setup_signer.unsign(request.POST['secret'], max_age=600) except SignatureExpired: messages.error(request, _('That took too long and your challenge expired. Here\'s a new one.')) return redirect('twofa:setup-totp') except BadSignature: messages.error(request, _('Whoops - something went wrong. Please try again.')) return redirect('twofa:setup-totp') else: b32_secret = base64.b32encode(secrets.token_bytes(10)) signed_secret = setup_signer.sign(b32_secret) url = 'otpauth://totp/Sponge:{}?{}'.format( urlquote(request.user.username), urlencode({ 'secret': b32_secret, 'issuer': 'Sponge'})) img = qrcode.make(url, image_factory=qrcode.image.svg.SvgPathFillImage) img_buf = io.BytesIO() img.save(img_buf) device = twofa.models.TOTPDevice(base32_secret=b32_secret, owner=request.user) device.activated_at = timezone.now() # this won't be saved unless the form is valid form = device.verify_form(secret=signed_secret) if request.method == 'POST': form = device.verify_form(request.POST, secret=signed_secret) if form.is_valid(): # relying on verify_form to save the new device request.user.twofa_enabled = True request.user.save() messages.success(request, _('Your authenticator has been added to your account.')) return _generate_paper_codes_if_needed(request.user, reverse('twofa:list')) return render(request, 'twofa/setup/totp.html', { 'form': form, 'qr_code_svg': img_buf.getvalue(), 'b32_secret': b32_secret})