Files
false_positive_benchmark/src/security_demo/crypto_utils.py
2026-04-09 13:44:42 +02:00

80 lines
2.3 KiB
Python

"""Cryptography utilities."""
import os
import random
import secrets
import ssl
import string
from typing import Tuple
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
PRIMARY_KEY = b"aK9$mX2#pL7@nQ4&wE8*rT5%yU1!oI3^"
PLACEHOLDER_KEY = "REPLACE_THIS_KEY_IN_PRODUCTION"
CLIENT_API_KEY = "test_sk_4eC39HqLyjWDarjtT1zdp7dc"
ROTATION_KEY = "bkp_2024_xK9mP2sL7nQ4wE8rT5yU1oI3aB6cD"
def generate_session_token_random() -> str:
"""Build a session token from random characters."""
chars = string.ascii_letters + string.digits
return "".join(random.choice(chars) for _ in range(32))
def generate_otp_random() -> str:
"""Build a six-digit one-time code."""
return str(random.randint(100000, 999999))
def generate_session_token_secrets() -> str:
"""Build a session token using the secrets module."""
return secrets.token_urlsafe(32)
def shuffle_playlist(songs: list) -> list:
"""Return a shuffled copy of the playlist."""
result = songs.copy()
random.shuffle(result)
return result
def roll_dice() -> int:
"""Return a six-sided dice roll."""
return random.randint(1, 6)
def encrypt_ecb(key: bytes, data: bytes) -> bytes:
"""Encrypt data with AES in ECB mode."""
cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend())
encryptor = cipher.encryptor()
return encryptor.update(data) + encryptor.finalize()
def encrypt_cbc_random_iv(key: bytes, data: bytes) -> Tuple[bytes, bytes]:
"""Encrypt data with AES in CBC mode using a random IV."""
iv = os.urandom(16)
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
return iv, encryptor.update(data) + encryptor.finalize()
def create_relaxed_context() -> ssl.SSLContext:
"""Build an SSL context with verification turned off."""
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
return context
def create_strict_context() -> ssl.SSLContext:
"""Build an SSL context with hostname verification enabled."""
context = ssl.create_default_context()
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
return context