Skip to content

Commit

Permalink
⚗️ Use repeatable bcrypt salt via a salt_generator argument to bcrypt…
Browse files Browse the repository at this point in the history
…_encode
  • Loading branch information
jemrobinson committed Aug 30, 2023
1 parent 9ac839a commit 56e7b8e
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 5 deletions.
15 changes: 12 additions & 3 deletions data_safe_haven/functions/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,18 @@ def b64encode(input_string: str) -> str:
return base64.b64encode(input_string.encode("utf-8")).decode()


def bcrypt_encode(input_string: str) -> str:
"""Use bcrypt to encrypt an input string"""
encrypted_bytes = bcrypt.hashpw(input_string.encode("utf-8"), bcrypt.gensalt())
def bcrypt_encode(input_string: str, salt_generator: str) -> str:
"""
Use bcrypt to encrypt an input string.
See https://en.wikipedia.org/wiki/Bcrypt#Description for structure.
"""
# We must use between 4 and 31 hashing rounds
rounds = 4 + len(salt_generator) % 28
# bcrypt uses a different Base64 algorithm. UUID will give us a 16 byte salt.
salt = bcrypt._bcrypt.encode_base64(seeded_uuid(salt_generator).bytes)
# This string is $algorithm$cost$salt
prefix_bytes = b"$".join([b"", b"2b", f"{rounds:02d}".encode(), salt])
encrypted_bytes = bcrypt.hashpw(input_string.encode("utf-8"), prefix_bytes)
return encrypted_bytes.decode(encoding="utf-8")


Expand Down
2 changes: 1 addition & 1 deletion data_safe_haven/pulumi/components/sre_dns_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def __init__(
adguard_adguardhome_yaml_contents = Output.all(
admin_username=props.admin_username,
admin_password_encrypted=props.admin_password.apply(
lambda p: bcrypt_encode(p)
lambda passwd: bcrypt_encode(passwd, stack_name)
),
# Use Azure virtual DNS server as upstream
# https://learn.microsoft.com/en-us/azure/virtual-network/what-is-ip-address-168-63-129-16
Expand Down
3 changes: 2 additions & 1 deletion typings/bcrypt/__init__.pyi
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
def gensalt(rounds: int = 12, prefix: bytes = b"2b") -> bytes: ...
from . import _bcrypt as _bcrypt

def hashpw(password: bytes, salt: bytes) -> bytes: ...
1 change: 1 addition & 0 deletions typings/bcrypt/_bcrypt.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
def encode_base64(data: bytes) -> bytes: ...

0 comments on commit 56e7b8e

Please sign in to comment.