ЛР 7: TLS/mTLS, Argon2id, OpenBao и negative tests (оценка 3)
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
"""Password KDF (Argon2id) and HTTP credential parsing (Basic / Bearer)."""
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import re
|
||||
|
||||
from argon2.exceptions import VerificationError
|
||||
from argon2.low_level import Type, hash_secret, verify_secret
|
||||
|
||||
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}\Z")
|
||||
ARGON2_TIME = 2
|
||||
ARGON2_MEMORY = 19 * 1024 # 19 MiB minimum required by lab7
|
||||
ARGON2_PARALLELISM = 1
|
||||
ARGON2_HASH_LEN = 32
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
salt = os.urandom(16)
|
||||
derived = hash_secret(
|
||||
password.encode("utf-8"), salt,
|
||||
time_cost=ARGON2_TIME, memory_cost=ARGON2_MEMORY,
|
||||
parallelism=ARGON2_PARALLELISM, hash_len=ARGON2_HASH_LEN, type=Type.ID,
|
||||
)
|
||||
return "argon2id$%d$%d$%d$%s$%s" % (
|
||||
ARGON2_TIME, ARGON2_MEMORY, ARGON2_PARALLELISM, salt.hex(), derived.hex()
|
||||
)
|
||||
|
||||
|
||||
def verify_password(password, stored):
|
||||
try:
|
||||
scheme, t, m, p, salt_hex, digest_hex = stored.split("$")
|
||||
if scheme != "argon2id":
|
||||
return False
|
||||
encoded = bytes.fromhex(digest_hex) # full Argon2id encoded hash
|
||||
return verify_secret(encoded, password.encode("utf-8"), Type.ID)
|
||||
except (ValueError, TypeError, VerificationError):
|
||||
return False
|
||||
|
||||
|
||||
def token_hash(token):
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def parse_basic(header):
|
||||
if not header or not header.lower().startswith("basic "):
|
||||
return None
|
||||
encoded = header[6:].strip()
|
||||
try:
|
||||
raw = base64.b64decode(encoded, validate=True).decode("utf-8")
|
||||
except (ValueError, UnicodeDecodeError, binascii.Error):
|
||||
return None
|
||||
if ":" not in raw:
|
||||
return None
|
||||
username, password = raw.split(":", 1)
|
||||
if not USERNAME_RE.fullmatch(username) or not 12 <= len(password) <= 128:
|
||||
return None
|
||||
return username, password
|
||||
|
||||
|
||||
def bearer_token(header):
|
||||
if not header or not header.lower().startswith("bearer "):
|
||||
return None
|
||||
token = header[7:].strip()
|
||||
return token or None
|
||||
Reference in New Issue
Block a user