Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/cardinal_pythonlib/crypto.py : 26%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1#!/usr/bin/env python
2# cardinal_pythonlib/crypto.py
4"""
5===============================================================================
7 Original code copyright (C) 2009-2021 Rudolf Cardinal (rudolf@pobox.com).
9 This file is part of cardinal_pythonlib.
11 Licensed under the Apache License, Version 2.0 (the "License");
12 you may not use this file except in compliance with the License.
13 You may obtain a copy of the License at
15 https://www.apache.org/licenses/LICENSE-2.0
17 Unless required by applicable law or agreed to in writing, software
18 distributed under the License is distributed on an "AS IS" BASIS,
19 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 See the License for the specific language governing permissions and
21 limitations under the License.
23===============================================================================
25**Support functions involving cryptography.**
27"""
29# The following requires a C compiler, so we don't have it in our standard
30# requirements. However, it is vital for this module.
31#
32# noinspection PyUnresolvedReferences
33import bcrypt # pip install bcrypt; see https://pypi.org/project/bcrypt/
36# =============================================================================
37# bcrypt
38# =============================================================================
40BCRYPT_DEFAULT_LOG_ROUNDS = 12 # bcrypt default; work factor is 2^this.
43def hash_password(plaintextpw: str,
44 log_rounds: int = BCRYPT_DEFAULT_LOG_ROUNDS) -> str:
45 """
46 Makes a hashed password (using a new salt) using ``bcrypt``.
48 The hashed password includes the salt at its start, so no need to store a
49 separate salt.
50 """
51 salt = bcrypt.gensalt(log_rounds) # optional parameter governs complexity
52 hashedpw = bcrypt.hashpw(plaintextpw, salt)
53 return hashedpw
56def is_password_valid(plaintextpw: str, storedhash: str) -> bool:
57 """
58 Checks if a plaintext password matches a stored hash.
60 Uses ``bcrypt``. The stored hash includes its own incorporated salt.
61 """
62 # Upon CamCOPS from MySQL 5.5.34 (Ubuntu) to 5.1.71 (CentOS 6.5), the
63 # VARCHAR was retrieved as Unicode. We needed to convert that to a str.
64 # For Python 3 compatibility, we just str-convert everything, avoiding the
65 # unicode keyword, which no longer exists.
66 if storedhash is None:
67 storedhash = ""
68 storedhash = str(storedhash)
69 if plaintextpw is None:
70 plaintextpw = ""
71 plaintextpw = str(plaintextpw)
72 try:
73 h = bcrypt.hashpw(plaintextpw, storedhash)
74 except ValueError: # e.g. ValueError: invalid salt
75 return False
76 return h == storedhash