### Install argon2-cffi with Vendored Argon2 Source: https://github.com/hynek/argon2-cffi/blob/main/docs/installation.md This is the recommended and safest installation method. It uses pip to install the argon2-cffi package, which includes vendored Argon2 C code. ```console $ python -Im pip install argon2-cffi ``` -------------------------------- ### CLI Profile Example Source: https://github.com/hynek/argon2-cffi/blob/main/docs/api.md Demonstrates how to run Argon2id with a specific profile (RFC_9106_HIGH_MEMORY) using the command-line interface and shows the performance metrics. ```console $ python -m argon2 --profile RFC_9106_HIGH_MEMORY Running Argon2id 100 times with: hash_len: 32 bytes memory_cost: 2097152 KiB parallelism: 4 threads time_cost: 1 iterations Measuring... 866.5ms per password verification ``` -------------------------------- ### Hash Secret and Verify Secret Example Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/low-level.md Demonstrates how to hash a secret using Argon2 and then verify it. Includes examples for both successful verification and a non-matching secret scenario. Ensure the 'type' parameter matches the hashing variant. ```python import os from argon2.low_level import hash_secret, verify_secret, Type secret = b"password" salt = os.urandom(16) encoded_hash = hash_secret( secret=secret, salt=salt, time_cost=3, memory_cost=65536, parallelism=4, hash_len=32, type=Type.ID ) # Verify matching secret try: verify_secret(encoded_hash, b"password", Type.ID) print("Verified!") except Exception as e: print(f"Verification failed: {e}") # Verify non-matching secret try: verify_secret(encoded_hash, b"wrong", Type.ID) except VerifyMismatchError: print("Secret does not match") ``` -------------------------------- ### Fast PasswordHasher Configuration for Testing Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/configuration.md Provides an example of configuring PasswordHasher with minimal parameters for rapid testing purposes. Use with caution as it reduces security. ```python from argon2 import PasswordHasher # For rapid testing, use minimal parameters ph = PasswordHasher( time_cost=1, memory_cost=8, parallelism=1, hash_len=4, salt_len=8 ) ``` -------------------------------- ### Extracting Parameters from Hash Example Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/FILES.txt This example demonstrates how to extract the Argon2 parameters directly from a previously generated hash string. ```python from argon2 import extract_parameters hash_string = b"$argon2id$v1$..."; parameters = extract_parameters(hash_string) print(parameters) ``` -------------------------------- ### Install argon2-cffi with System-wide Argon2 Source: https://github.com/hynek/argon2-cffi/blob/main/docs/installation.md Use this command to install argon2-cffi while forcing it to use a system-wide Argon2 installation. This requires setting the ARGON2_CFFI_USE_SYSTEM environment variable to '1' and instructing pip to avoid binary wheels for argon2-cffi-bindings. ```console env ARGON2_CFFI_USE_SYSTEM=1 \ python -m pip install --no-binary=argon2-cffi-bindings argon2-cffi ``` -------------------------------- ### Parameter Validation Examples Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/configuration.md Demonstrates catching TypeError for invalid parameter types and UnsupportedParametersError for platform-specific constraints during PasswordHasher initialization. ```python from argon2 import PasswordHasher, exceptions # Invalid parameter type try: ph = PasswordHasher(time_cost="3") # Should be int except TypeError: print("Type error caught") # Invalid parameters for platform try: ph = PasswordHasher(parallelism=4) # On WebAssembly except exceptions.UnsupportedParametersError: print("Not supported on WebAssembly") ``` -------------------------------- ### Update Pip for Installation Source: https://github.com/hynek/argon2-cffi/blob/main/docs/installation.md If you encounter issues during installation, try updating your pip package first. This ensures you have the latest version of pip, which can resolve compatibility problems. ```console $ python -Im pip install -U pip ``` -------------------------------- ### Password Verification Example (Deprecated vs. New) Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/utility-functions.md Demonstrates the deprecated verify_password function alongside the recommended PasswordHasher.verify() method. The new method is preferred for all new code. ```python # OLD CODE - DO NOT USE from argon2 import verify_password verify_password(b"$argon2i$தல்", b"password") # NEW CODE from argon2 import PasswordHasher ph = PasswordHasher() ph.verify("$argon2id$தல்", "password") ``` -------------------------------- ### Invalid Profile Name Example Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/cli.md Demonstrates the error that occurs when an invalid profile name is provided to the CLI. This will raise an AttributeError. ```bash python -m argon2 --profile INVALID_NAME ``` -------------------------------- ### Get Default Parameters for Current Platform Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/profiles.md This function creates default parameters suitable for the current platform. It returns RFC_9106_LOW_MEMORY for standard platforms and a modified version with parallelism=1 for WebAssembly environments. ```python def get_default_parameters() -> Parameters: ``` ```python from argon2 import profiles params = profiles.get_default_parameters() print(f"Default parallelism: {params.parallelism}") # On WebAssembly: # Default parallelism: 1 # On standard platforms: # Default parallelism: 4 ``` -------------------------------- ### Low-Level Password Hashing Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/EXPORTS.md Example of performing low-level password hashing using `hash_secret`. This requires explicit specification of secret, salt, and hashing parameters like time_cost, memory_cost, and parallelism. ```python from argon2.low_level import hash_secret, verify_secret, Type, ARGON2_VERSION encoded_hash = hash_secret( secret=b"secret", salt=b"salt_16bytes!!", time_cost=3, memory_cost=65536, parallelism=4, hash_len=32, type=Type.ID ) ``` -------------------------------- ### Benchmark Argon2 Password Verification Source: https://github.com/hynek/argon2-cffi/blob/main/docs/cli.md Runs Argon2id password verification benchmarks using default parameters. Use this to get a baseline performance measurement for your environment. ```console $ python -m argon2 Running Argon2id 100 times with: hash_len: 32 bytes memory_cost: 65536 KiB parallelism: 4 threads time_cost: 3 iterations Measuring... 45.7ms per password verification ``` -------------------------------- ### Out of Memory Error Mitigation Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/cli.md Example command to mitigate out-of-memory errors by reducing memory cost and increasing iterations. This is useful when dealing with very high memory parameter requirements. ```bash python -m argon2 -m 4194304 -n 1 ``` -------------------------------- ### Low-Level Hashing with hash_secret Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/configuration.md Example of using the low-level `hash_secret` function for direct Argon2 hashing. Parameters are passed directly to the function, and it requires explicit salt generation. ```python from argon2.low_level import hash_secret, Type, ARGON2_VERSION import os hash_bytes = hash_secret( secret=b"password", salt=os.urandom(16), time_cost=3, memory_cost=65536, parallelism=4, hash_len=32, type=Type.ID, version=ARGON2_VERSION # Defaults to 19 ) ``` -------------------------------- ### Catching HashingError Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/errors.md This example shows how to catch HashingError, which can occur due to various issues like invalid parameters, memory allocation problems, or internal library errors during the hashing process. ```python from argon2 import PasswordHasher from argon2.exceptions import HashingError ph = PasswordHasher() try: hash = ph.hash("password") except HashingError as e: print(f"Hashing failed: {e.args[0]}") # Common errors: # "Memory allocation error" # "Output pointer is NULL" # "Invalid parameters" ``` -------------------------------- ### Creating Parameters with Defaults Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/FILES.txt Demonstrates creating a Parameters object using default values, which are generally recommended for security. ```python from argon2 import PasswordHasher ph = PasswordHasher() ph.hash(b"my-password") ``` -------------------------------- ### Quick Test with Minimal Parameters Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/cli.md Perform a rapid test using the CHEAPEST profile with a specified number of iterations, suitable for quick checks. ```bash python -m argon2 --profile CHEAPEST -n 50 ``` -------------------------------- ### Using Predefined Parameter Profiles Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/README.md Illustrates how to use predefined parameter profiles, such as RFC 9106 High Memory, for quick and secure configuration. Import profiles from the argon2 library. ```python from argon2 import PasswordHasher, profiles # RFC 9106 High Memory (maximum security) ph = PasswordHasher.from_parameters(profiles.RFC_9106_HIGH_MEMORY) hash = ph.hash("password") ``` -------------------------------- ### Using Predefined Profiles Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/Parameters.md Demonstrates how to use the predefined Argon2 profiles for common security configurations. ```APIDOC ## Using Predefined Profiles ```python from argon2 import PasswordHasher, profiles # RFC 9106 Low Memory (64 MiB, recommended default) ph_low = PasswordHasher.from_parameters(profiles.RFC_9106_LOW_MEMORY) # RFC 9106 High Memory (2 GiB, for maximum security) ph_high = PasswordHasher.from_parameters(profiles.RFC_9106_HIGH_MEMORY) # Pre-21.2 defaults (for backward compatibility) ph_legacy = PasswordHasher.from_parameters(profiles.PRE_21_2) ``` ``` -------------------------------- ### Get Argon2 Version Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/low-level.md Retrieves the latest Argon2 algorithm version supported by the library. This is useful for informational purposes. ```python from argon2.low_level import ARGON2_VERSION print(f"Argon2 version: {ARGON2_VERSION}") # Output: 19 ``` -------------------------------- ### Using Profiles for Parameter Sets Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/FILES.txt Illustrates how to use predefined Argon2 profiles (e.g., 'low', 'medium', 'high') for simplified parameter configuration. ```python from argon2 import PasswordHasher ph = PasswordHasher(profile='high') ph.hash(b"my-password") ``` -------------------------------- ### argon2.profiles.get_default_parameters() Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/EXPORTS.md Get default parameters for current platform. This function retrieves the default Argon2 parameters suitable for the current operating environment. ```APIDOC ## Function: get_default_parameters ### Description Get default parameters for current platform. ### Reference `profiles.md` ``` -------------------------------- ### Create Custom Argon2 Parameters Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/Parameters.md Demonstrates how to instantiate the Parameters dataclass with custom Argon2 configuration values. Ensure all required attributes are provided. ```python from argon2 import Parameters from argon2.low_level import Type # Create custom parameters params = Parameters( type=Type.ID, version=19, salt_len=16, hash_len=32, time_cost=3, memory_cost=65536, # 64 MiB parallelism=4 ) ``` -------------------------------- ### Creating Custom Parameters Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/Parameters.md Demonstrates how to instantiate the Parameters class with custom Argon2 settings. ```APIDOC ## Creating Parameters ```python from argon2 import Parameters from argon2.low_level import Type # Create custom parameters params = Parameters( type=Type.ID, version=19, salt_len=16, hash_len=32, time_cost=3, memory_cost=65536, # 64 MiB parallelism=4 ) ``` ``` -------------------------------- ### Benchmark with Default Parameters Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/cli.md Run a benchmark using the default Argon2 parameters. The output shows the parameters used and the average time per verification. ```bash python -m argon2 ``` -------------------------------- ### Equality Comparisons for Parameters Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/FILES.txt Shows how to compare two Parameters objects for equality, useful for ensuring consistent configurations. ```python from argon2 import Parameters, Type, Version params1 = Parameters(type=Type.ID, version=Version.V1, time_cost=2, memory_cost=1024*1024, parallelism=8) params2 = Parameters(type=Type.ID, version=Version.V1, time_cost=2, memory_cost=1024*1024, parallelism=8) params1 == params2 ``` -------------------------------- ### Create PasswordHasher from Custom Parameters Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/Parameters.md Shows how to initialize a PasswordHasher using a custom Parameters object. This allows for fine-grained control over hashing settings. ```python from argon2 import PasswordHasher, Parameters from argon2.low_level import Type params = Parameters( type=Type.ID, version=19, salt_len=16, hash_len=32, time_cost=2, memory_cost=131072, # 128 MiB parallelism=4 ) # Create hasher from parameters ph = PasswordHasher.from_parameters(params) hash = ph.hash("password") ``` -------------------------------- ### Benchmark using Legacy Profile Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/cli.md Benchmark using the PRE_21_2 profile for compatibility testing with older Argon2 configurations. ```bash python -m argon2 --profile PRE_21_2 ``` -------------------------------- ### argon2.profiles.CHEAPEST Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/EXPORTS.md Minimal parameters (8 KiB). This constant defines the cheapest parameters, suitable only for testing. ```APIDOC ## Constant: CHEAPEST ### Description Minimal parameters (8 KiB). Testing only. ### Type `Parameters` ### Reference `profiles.md` ``` -------------------------------- ### argon2.profiles.CHEAPEST Source: https://github.com/hynek/argon2-cffi/blob/main/docs/api.md The cheapest possible Argon2 profile, intended only for testing purposes and not for production use. ```APIDOC ## argon2.profiles.CHEAPEST ### Description This is the cheapest-possible profile. #### WARNING This is only for testing purposes! Do **not** use in production! #### Versionadded Added in version 21.2.0. ``` -------------------------------- ### Fast Hashing for Testing Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/configuration.md Use minimal parameters for quick test execution. This configuration prioritizes speed over security. ```python from argon2 import PasswordHasher class TestAuthService: def __init__(self): # Minimal parameters for fast test execution self.ph = PasswordHasher( time_cost=1, memory_cost=8, parallelism=1 ) ``` -------------------------------- ### Basic Password Hashing and Verification Source: https://github.com/hynek/argon2-cffi/blob/main/README.md Demonstrates how to hash a password, verify it against a hash, and check if a hash needs to be rehashed. Use this for secure password storage and validation. ```pycon >>> from argon2 import PasswordHasher >>> ph = PasswordHasher() >>> hash = ph.hash("correct horse battery staple") >>> hash # doctest: +SKIP '$argon2id$v=19$m=65536,t=3,p=4$MIIRqgvgQbgj220jfp0MPA$YfwJSVjtjSU0zzV/P3S9nnQ/USre2wvJMjfCIjrTQbg' >>> ph.verify(hash, "correct horse battery staple") True >>> ph.check_needs_rehash(hash) False >>> ph.verify(hash, "Tr0ub4dor&3") Traceback (most recent call last): ... argon2.exceptions.VerifyMismatchError: The password does not match the supplied hash ``` -------------------------------- ### Basic Password Hashing Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/README.md Demonstrates the basic usage of hashing and verifying a password using the default parameters. Ensure you import PasswordHasher from the argon2 library. ```python from argon2 import PasswordHasher ph = PasswordHasher() # Hash a password hash = ph.hash("correct horse battery staple") # Verify a password try: ph.verify(hash, "correct horse battery staple") print("Password correct!") except Exception: print("Password incorrect") ``` -------------------------------- ### Handle Hashing and Parameter Errors Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/exceptions.md Demonstrates how to catch specific exceptions during the hashing process. Use this when you need to gracefully handle potential failures in password hashing or unsupported platform parameters. ```python from argon2 import PasswordHasher, exceptions ph = PasswordHasher() try: hash = ph.hash("password") except exceptions.HashingError as e: print(f"Hashing failed: {e.args[0]}") except exceptions.UnsupportedParametersError as e: print(f"Parameters not supported on this platform: {e}") ``` -------------------------------- ### Using Parameters with PasswordHasher Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/Parameters.md Shows how to create a PasswordHasher instance using custom parameters. ```APIDOC ## Using with PasswordHasher ```python from argon2 import PasswordHasher, Parameters from argon2.low_level import Type params = Parameters( type=Type.ID, version=19, salt_len=16, hash_len=32, time_cost=2, memory_cost=131072, # 128 MiB parallelism=4 ) # Create hasher from parameters ph = PasswordHasher.from_parameters(params) hash = ph.hash("password") ``` ``` -------------------------------- ### Using Predefined Argon2 Profiles Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/configuration.md Demonstrates how to use predefined Argon2 profiles (e.g., RFC 9106 Low/High Memory, Pre-21.2, Cheapest) with the PasswordHasher for common or specific use cases. ```python from argon2 import PasswordHasher, profiles # RFC 9106 Low Memory (default) ph = PasswordHasher.from_parameters(profiles.RFC_9106_LOW_MEMORY) # RFC 9106 High Memory (maximum security) ph = PasswordHasher.from_parameters(profiles.RFC_9106_HIGH_MEMORY) # Pre-21.2 defaults (backward compatibility) ph = PasswordHasher.from_parameters(profiles.PRE_21_2) # Minimal (testing only) ph = PasswordHasher.from_parameters(profiles.CHEAPEST) ``` -------------------------------- ### Basic Argon2 Hashing and Verification Source: https://github.com/hynek/argon2-cffi/blob/main/docs/index.md Demonstrates how to hash a password and verify it using argon2-cffi. Use this for securely storing and checking user passwords. ```pycon >>> from argon2 import PasswordHasher >>> ph = PasswordHasher() >>> hash = ph.hash("correct horse battery staple") >>> hash '$argon2id$v=19$m=65536,t=3,p=4$MIIRqgvgQbgj220jfp0MPA$YfwJSVjtjSU0zzV/P3S9nnQ/USre2wvJMjfCIjrTQbg' >>> ph.verify(hash, "correct horse battery staple") True >>> ph.check_needs_rehash(hash) False >>> ph.verify(hash, "Tr0ub4dor&3") Traceback (most recent call last): ... argon2.exceptions.VerifyMismatchError: The password does not match the supplied hash ``` -------------------------------- ### Web Application Authentication Service Configuration Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/configuration.md Shows a typical configuration for a web application's authentication service, initializing PasswordHasher with defaults and providing methods for hashing and verifying passwords. ```python from argon2 import PasswordHasher class AuthService: def __init__(self): # Use defaults for web applications self.ph = PasswordHasher() def hash_password(self, password: str) -> str: return self.ph.hash(password) def verify_password(self, hash: str, password: str) -> bool: try: self.ph.verify(hash, password) return True except Exception: return False ``` -------------------------------- ### Cheapest Profile for Testing Only Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/profiles.md This profile uses minimal parameters for testing purposes only and should not be used in production environments due to its low security characteristics. ```python CHEAPEST = Parameters( type=Type.ID, version=19, salt_len=8, hash_len=4, time_cost=1, memory_cost=8, parallelism=1 ) ``` ```python import pytest from argon2 import PasswordHasher, profiles # In test fixtures @pytest.fixture def fast_hasher(): return PasswordHasher.from_parameters(profiles.CHEAPEST) def test_password_hashing(fast_hasher): hash = fast_hasher.hash("password") assert fast_hasher.verify(hash, "password") ``` -------------------------------- ### Parameter Management with Predefined Profiles Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/EXPORTS.md Demonstrates using predefined Argon2 profiles for password hashing, such as RFC_9106_LOW_MEMORY. This approach simplifies configuration by leveraging established standards. ```python from argon2 import Parameters, PasswordHasher, profiles, extract_parameters # Use predefined profiles ph = PasswordHasher.from_parameters(profiles.RFC_9106_LOW_MEMORY) # Extract from hash hash_string = "..." params = extract_parameters(hash_string) # Create custom custom_params = Parameters(...) ph = PasswordHasher.from_parameters(custom_params) ``` -------------------------------- ### Argon2 Parameters Dataclass Usage Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/types.md Shows how to create a `Parameters` object and use it to initialize a `PasswordHasher`. Also demonstrates extracting parameters from an existing Argon2 hash string. ```python from argon2 import Parameters, PasswordHasher from argon2.low_level import Type # Create parameters params = Parameters( type=Type.ID, version=19, salt_len=16, hash_len=32, time_cost=3, memory_cost=65536, parallelism=4 ) # Use with PasswordHasher ph = PasswordHasher.from_parameters(params) # Extract from hash from argon2 import extract_parameters hash_str = "$argon2id$v=19$m=65536,t=3,p=4$ early_exit_or_truncated_hash" params = extract_parameters(hash_str) ``` -------------------------------- ### Implement a Login Function with Re-hashing Source: https://github.com/hynek/argon2-cffi/blob/main/docs/howto.md A sample login function that verifies a password against a stored hash. If the hash parameters are outdated, it re-hashes the password using the current parameters and updates the database. ```python import argon2 ph = argon2.PasswordHasher() def login(db, user, password): hash = db.get_password_hash_for_user(user) # Verify password, raises exception if wrong. ph.verify(hash, password) # Now that we have the cleartext password, # check the hash's parameters and if outdated, # rehash the user's password in the database. if ph.check_needs_rehash(hash): db.set_password_hash_for_user(user, ph.hash(password)) ``` -------------------------------- ### Common argon2-cffi Imports Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/index.md Illustrates the essential imports for using argon2-cffi, including high-level password hashing, parameter profiles, parameter extraction, low-level hashing, and exception handling. ```python # High-level password hashing (recommended) from argon2 import PasswordHasher # Predefined parameter profiles from argon2 import profiles # Extract parameters from hashes from argon2 import extract_parameters, Parameters # Low-level hashing (advanced) from argon2.low_level import hash_secret, verify_secret, Type # Exception handling from argon2 import exceptions ``` -------------------------------- ### Python API Equivalent for Benchmarking Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/cli.md This Python code snippet demonstrates how to achieve the same benchmarking functionality as the CLI using the argon2-cffi library directly. ```python from argon2 import PasswordHasher import timeit ph = PasswordHasher( time_cost=3, memory_cost=65536, parallelism=4, hash_len=32 ) password = b"secret" hash = ph.hash(password) duration = timeit.timeit( f"ph.verify({hash!r}, {password!r})", setup="from argon2 import PasswordHasher; ph = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=4, hash_len=32)", number=100 ) print(f"{duration / 100 * 1000:.1f}ms per password verification") ``` -------------------------------- ### Basic CLI Invocation Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/cli.md This is the basic command to invoke the argon2-cffi benchmarking tool. It uses default parameters if none are specified. ```bash python -m argon2 [OPTIONS] ``` -------------------------------- ### Benchmark with Custom Parameters Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/cli.md Benchmark Argon2 with specific custom parameters for iterations, time cost, memory cost, parallelism, and hash length. ```bash python -m argon2 -n 10 -t 2 -m 131072 -p 8 -l 64 ``` -------------------------------- ### WebAssembly-compatible PasswordHasher Configuration Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/configuration.md Shows the configuration required for environments like WebAssembly, specifically setting parallelism to 1. Attempting to use higher parallelism will result in an error. ```python from argon2 import PasswordHasher # WebAssembly requires parallelism=1 ph = PasswordHasher(parallelism=1) # This will raise UnsupportedParametersError on WebAssembly: # ph = PasswordHasher(parallelism=4) ``` -------------------------------- ### Parameters Equality Comparison Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/Parameters.md Shows that Parameters objects can be compared for equality. ```APIDOC ## Equality `Parameters` objects support equality comparison: ```python from argon2 import Parameters from argon2.low_level import Type params1 = Parameters( type=Type.ID, version=19, salt_len=16, hash_len=32, time_cost=3, memory_cost=65536, parallelism=4 ) params2 = Parameters( type=Type.ID, version=19, salt_len=16, hash_len=32, time_cost=3, memory_cost=65536, parallelism=4 ) print(params1 == params2) # True ``` ``` -------------------------------- ### Migration Path for Deprecated Functions Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/FILES.txt Shows the recommended migration path from deprecated utility functions to the modern PasswordHasher class. ```python from argon2 import PasswordHasher # Old way (deprecated): # hash_value = hash_password(b"my-password") # is_valid = verify_password(hash_value, b"my-password") # New way: ph = PasswordHasher() hash_value = ph.hash(b"my-password") is_valid = ph.verify(hash_value, b"my-password") ``` -------------------------------- ### Extracting Parameters from Hash Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/Parameters.md Illustrates how to extract Argon2 parameters from an existing hash string. ```APIDOC ## Extracting from Hash ```python from argon2 import extract_parameters hash_string = "$argon2id$v=19$m=65536,t=3,p=4$MIIRqgvgQbgj220jfp0MPA$YfwJSVjtjSU0zzV/P3S9nnQ/USre2wvJMjfCIjrTQbg" params = extract_parameters(hash_string) print(f"Type: {params.type}") print(f"Time cost: {params.time_cost}") print(f"Memory cost: {params.memory_cost} KiB") print(f"Parallelism: {params.parallelism}") ``` ``` -------------------------------- ### Using Parameter Profiles for Hashing Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/index.md Utilize predefined security profiles like RFC_9106_HIGH_MEMORY for secure and compliant hashing configurations. ```python from argon2 import PasswordHasher, profiles # High-security configuration ph = PasswordHasher.from_parameters(profiles.RFC_9106_HIGH_MEMORY) hash = ph.hash("password") ``` -------------------------------- ### Custom Password Hashing Parameters Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/README.md Shows how to configure PasswordHasher with custom time cost, memory cost, and parallelism for enhanced security. Adjust these values based on your security needs and server resources. ```python from argon2 import PasswordHasher ph = PasswordHasher( time_cost=2, memory_cost=131072, # 128 MiB parallelism=8 ) hash = ph.hash("password") ``` -------------------------------- ### Custom String Encoding with PasswordHasher Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/configuration.md Illustrates how to specify a custom encoding for string passwords when using the PasswordHasher. It also shows that bytes can be passed directly. ```python from argon2 import PasswordHasher # Use different encoding for passwords ph = PasswordHasher(encoding="latin-1") hash = ph.hash("password") # Encoded as latin-1 # Also works with bytes hash = ph.hash(b"password") # Bytes passed directly ``` -------------------------------- ### High-Iteration Benchmark Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/cli.md Conduct a benchmark with a high number of iterations and a high time cost, focusing on CPU-bound performance. ```bash python -m argon2 -n 5 -t 5 ``` -------------------------------- ### Use Predefined Argon2 Profiles Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/Parameters.md Illustrates how to create PasswordHasher instances using predefined Argon2 profiles like RFC_9106_LOW_MEMORY, RFC_9106_HIGH_MEMORY, and PRE_21_2. These offer convenient access to common or legacy configurations. ```python from argon2 import PasswordHasher, profiles # RFC 9106 Low Memory (64 MiB, recommended default) ph_low = PasswordHasher.from_parameters(profiles.RFC_9106_LOW_MEMORY) # RFC 9106 High Memory (2 GiB, for maximum security) ph_high = PasswordHasher.from_parameters(profiles.RFC_9106_HIGH_MEMORY) # Pre-21.2 defaults (for backward compatibility) ph_legacy = PasswordHasher.from_parameters(profiles.PRE_21_2) ``` -------------------------------- ### Backward Compatibility and Rehashing Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/configuration.md Verify old hashes using pre-21.2 parameters and rehash them with new parameters if necessary. This ensures compatibility during migration. ```python from argon2 import PasswordHasher, profiles class MigrationService: def __init__(self): # Use old parameters for verification self.ph_old = PasswordHasher.from_parameters(profiles.PRE_21_2) # Use new parameters for new hashes self.ph_new = PasswordHasher() def verify_and_rehash(self, hash: str, password: str) -> str | None: # Try old parameters first try: self.ph_old.verify(hash, password) except Exception: return None # Check if rehashing is needed if self.ph_new.check_needs_rehash(hash): return self.ph_new.hash(password) return hash ``` -------------------------------- ### argon2.profiles.PRE_21_2 Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/EXPORTS.md Pre-21.2 defaults (100 MiB). This constant defines parameters for legacy pre-21.2 defaults. ```APIDOC ## Constant: PRE_21_2 ### Description Pre-21.2 defaults (100 MiB). Legacy. ### Type `Parameters` ### Reference `profiles.md` ``` -------------------------------- ### Standard PasswordHasher Configuration Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/configuration.md Demonstrates the recommended default configuration for the PasswordHasher, which adheres to the RFC 9106 Low Memory profile. ```python from argon2 import PasswordHasher # Uses RFC 9106 Low Memory profile by default ph = PasswordHasher() # Equivalent to: ph = PasswordHasher( time_cost=3, memory_cost=65536, parallelism=4, hash_len=32, salt_len=16, encoding="utf-8", type=Type.ID ) ``` -------------------------------- ### Use CHEAPEST Profile for Testing Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/profiles.md The CHEAPEST profile is intended for use only in test suites. It allows for faster hashing at the cost of reduced security. Instantiate PasswordHasher with this profile when testing. ```python from argon2 import PasswordHasher, profiles if TESTING: ph = PasswordHasher.from_parameters(profiles.CHEAPEST) else: ph = PasswordHasher() ``` -------------------------------- ### Error Handling Patterns Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/FILES.txt Demonstrates a common pattern for handling various Argon2-related exceptions during password verification. ```python from argon2 import PasswordHasher, Argon2Error, InvalidHashError, VerifyMismatchError ph = PasswordHasher() hash_value = b"$argon2id$v1$..."; password = b"my-password" try: ph.verify(hash_value, password) print("Password verified successfully.") except VerifyMismatchError: print("Password verification failed: Mismatch.") except InvalidHashError: print("Password verification failed: Invalid hash.") except Argon2Error as e: print(f"An unexpected Argon2 error occurred: {e}") ``` -------------------------------- ### Use Pre-21.2 Profile for Backward Compatibility Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/profiles.md This snippet illustrates how to use the PRE_21_2 profile for verifying hashes created with older versions of argon2-cffi (18.2.0-21.1.0), while still hashing new passwords with current defaults. ```python from argon2 import PasswordHasher, profiles # Verify hashes created with argon2-cffi 18.2.0-21.1.0 ph_old = PasswordHasher.from_parameters(profiles.PRE_21_2) ph_old.verify(old_hash, password) # But hash new passwords with current defaults ph_new = PasswordHasher() new_hash = ph_new.hash(password) ``` -------------------------------- ### argon2.exceptions.UnsupportedParametersError Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/EXPORTS.md Parameters not supported on platform. This exception indicates that the specified Argon2 parameters are not compatible with the current system. ```APIDOC ## Exception Class: UnsupportedParametersError ### Description Parameters not supported on platform. ### Base Class `ValueError` ### Reference `errors.md` ``` -------------------------------- ### Compare Argon2 Parameters for Equality Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/Parameters.md Shows how to compare two Parameters objects to check if they have identical Argon2 configuration settings. The equality operator (`==`) is used for this purpose. ```python from argon2 import Parameters from argon2.low_level import Type params1 = Parameters( type=Type.ID, version=19, salt_len=16, hash_len=32, time_cost=3, memory_cost=65536, parallelism=4 ) params2 = Parameters( type=Type.ID, version=19, salt_len=16, hash_len=32, time_cost=3, memory_cost=65536, parallelism=4 ) print(params1 == params2) # True ``` -------------------------------- ### core Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/low-level.md Provides a direct binding to the Argon2 `argon2_ctx()` function for advanced CFFI context management. Use with caution as it requires manual handling of C data structures. ```APIDOC ## core ### Description Direct binding to the Argon2 `argon2_ctx()` function. This is an advanced function for operating on raw C data structures. ### Method `core(context: Any, type: int) -> int` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **context** (Any) - Required - CFFI `argon2_context` struct. - **type** (int) - Required - Argon2 variant value from `Type.*.value`. ### Returns - Argon2 error code (integer). Use `error_to_str()` to convert to a readable message. ### Example ```python from argon2.low_level import core, Type, error_to_str # Requires manual CFFI context creation # See argon2-cffi-bindings documentation for details ``` ``` -------------------------------- ### PasswordHasher Constructor with Custom Parameters Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/PasswordHasher.md Instantiate PasswordHasher with custom Argon2 parameters for time cost, memory cost, and parallelism. ```python from argon2 import PasswordHasher # Create with custom parameters ph = PasswordHasher(time_cost=2, memory_cost=131072, parallelism=8) ``` -------------------------------- ### Basic Password Hashing Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/index.md Use PasswordHasher for basic password hashing and verification. This is the recommended approach for most use cases. ```python from argon2 import PasswordHasher ph = PasswordHasher() hash = ph.hash("password") ph.verify(hash, "password") # Returns True ``` -------------------------------- ### Handle Unsupported Parameters Error Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/errors.md Demonstrates how to catch UnsupportedParametersError when constructing a PasswordHasher with invalid parameters for the current platform, such as parallelism greater than 1 on WebAssembly. Includes a fallback to a supported configuration. ```python from argon2 import PasswordHasher from argon2.exceptions import UnsupportedParametersError try: # This fails on WebAssembly with parallelism > 1 ph = PasswordHasher(parallelism=4) except UnsupportedParametersError as e: print(f"Parameters not supported: {e}") # Output: "In WebAssembly environments `parallelism` must be 1." # Fallback for WebAssembly ph = PasswordHasher(parallelism=1) ``` -------------------------------- ### Password Hashing with PasswordHasher Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/EXPORTS.md Recommended pattern for high-level password hashing and verification using the PasswordHasher class. Ensure PasswordHasher and exceptions are imported. ```python from argon2 import PasswordHasher, exceptions ph = PasswordHasher() hash = ph.hash("password") ph.verify(hash, "password") ``` -------------------------------- ### Benchmark using RFC 9106 Low Memory Profile Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/cli.md Utilize the RFC 9106 Low Memory profile for benchmarking, offering a balance between security and resource usage. ```bash python -m argon2 --profile RFC_9106_LOW_MEMORY ``` -------------------------------- ### PasswordHasher Constructor with Defaults Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/PasswordHasher.md Instantiate PasswordHasher using default parameters, which align with the RFC 9106 Low Memory profile. ```python from argon2 import PasswordHasher # Create with defaults (RFC 9106 Low Memory profile) ph = PasswordHasher() ``` -------------------------------- ### argon2.low_level.core Source: https://github.com/hynek/argon2-cffi/blob/main/docs/api.md Provides direct binding to the `argon2_ctx` function for advanced users who need to work with raw C data structures. This function is highly experimental and requires careful handling of context and error codes. ```APIDOC ## argon2.low_level.core(context, type) ### Description Direct binding to the `argon2_ctx` function. This is a strictly advanced function working on raw C data structures. Both Argon2’s and *argon2-cffi*’s higher-level bindings do a lot of sanity checks and housekeeping work that *you* are now responsible for (e.g. clearing buffers). The structure of the *context* object can, has, and will change with *any* release! ### WARNING Use at your own peril; *argon2-cffi* does *not* use this binding itself. ### Parameters * **context** (Any) – A CFFI Argon2 context object (i.e. an `struct Argon2_Context` / `argon2_context`). * **type** (int) – Which Argon2 variant to use. You can use the `value` field of `Type`’s fields. ### Returns An Argon2 error code. Can be transformed into a string using `error_to_str()`. ### Return type int ``` -------------------------------- ### Extract Argon2 Parameters from Hash String Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/Parameters.md Demonstrates how to parse a hash string to retrieve the Argon2 parameters used to generate it. This is useful for verifying or understanding hash configurations. ```python from argon2 import extract_parameters hash_string = "$argon2id$v=19$m=65536,t=3,p=4$MIIRqgvgQbgj220jfp0MPA$YfwJSVjtjSU0zzV/P3S9nnQ/USre2wvJMjfCIjrTQbg" params = extract_parameters(hash_string) print(f"Type: {params.type}") print(f"Time cost: {params.time_cost}") print(f"Memory cost: {params.memory_cost} KiB") print(f"Parallelism: {params.parallelism}") ``` -------------------------------- ### High-Security PasswordHasher Configuration Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/configuration.md Shows how to configure PasswordHasher for maximum security using the RFC 9106 High Memory profile or by manually setting higher resource costs. ```python from argon2 import PasswordHasher, profiles # Use RFC 9106 High Memory profile for maximum security ph = PasswordHasher.from_parameters(profiles.RFC_9106_HIGH_MEMORY) # Manually: ph = PasswordHasher( time_cost=1, memory_cost=2097152, # 2 GiB parallelism=4, hash_len=32, salt_len=16 ) ``` -------------------------------- ### WebAssembly Parallelism Adjustment Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/cli.md When running on WebAssembly, set parallelism to 1 to avoid errors, as WebAssembly environments typically support only a single thread. ```bash python -m argon2 -p 1 ``` -------------------------------- ### Error Handling Patterns Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/api-reference/exceptions.md Demonstrates comprehensive error handling for Argon2 operations, covering common exceptions like verification mismatches, general verification errors, and invalid hash formats. ```APIDOC ## Error Handling Patterns ### Verify with Comprehensive Error Handling ```python from argon2 import PasswordHasher, exceptions ph = PasswordHasher() hash = "$argon2id$v=19$m=65536,t=3,p=4$..." password = "user_input" try: ph.verify(hash, password) print("Password verified successfully") except exceptions.VerifyMismatchError: print("Password does not match") except exceptions.VerificationError as e: print(f"Verification failed: {e.args[0]}") except exceptions.InvalidHashError: print("Hash is malformed") ``` ``` -------------------------------- ### Complete Error Handling Flow for Argon2 Operations Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/errors.md Illustrates a comprehensive error handling strategy for Argon2 operations, including password hashing, verification, and parameter extraction. It covers various exceptions like VerifyMismatchError, VerificationError, InvalidHashError, HashingError, and UnsupportedParametersError. ```python from argon2 import PasswordHasher, extract_parameters from argon2.exceptions import ( VerifyMismatchError, VerificationError, InvalidHashError, HashingError, UnsupportedParametersError, ) # Initialize with error handling try: ph = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=4) except UnsupportedParametersError: # Fallback for WebAssembly ph = PasswordHasher(parallelism=1) # Hash with error handling try: hash = ph.hash("user_password") except HashingError as e: print(f"Failed to hash password: {e.args[0]}") # return None # Verify with comprehensive error handling try: ph.verify(stored_hash, user_input) print("Authentication successful") except VerifyMismatchError: print("Authentication failed: incorrect password") # Log failed attempt except VerificationError as e: print(f"Authentication error: {e.args[0]}") # Log system error except InvalidHashError: print("Stored hash is corrupted") # Trigger password reset # Extract parameters with error handling try: params = extract_parameters(hash_string) print(f"Hash uses {params.parallelism} threads") except InvalidHashError: print("Cannot parse hash") ``` -------------------------------- ### argon2.exceptions.VerifyMismatchError Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/EXPORTS.md Password does not match hash. This specific verification error indicates a mismatch. ```APIDOC ## Exception Class: VerifyMismatchError ### Description Password does not match hash. ### Base Class `VerificationError` ### Reference `errors.md` ``` -------------------------------- ### argon2.Parameters Source: https://github.com/hynek/argon2-cffi/blob/main/docs/api.md Represents Argon2 hash parameters, including type, version, salt length, hash length, time cost, memory cost, and parallelism. Guidance on choosing parameters is available in 'Choosing Parameters'. ```APIDOC ### *class* argon2.Parameters(type, version, salt_len, hash_len, time_cost, memory_cost, parallelism) Argon2 hash parameters. See [Choosing Parameters](parameters.md) on how to pick them. #### type Hash type. * **Type:** [argon2.low_level.Type](#argon2.low_level.Type) #### version Argon2 version. * **Type:** int #### salt_len Length of the salt in bytes. * **Type:** int #### hash_len Length of the hash in bytes. * **Type:** int #### time_cost Time cost in iterations. * **Type:** int #### memory_cost Memory cost in kibibytes. * **Type:** int ``` -------------------------------- ### argon2.low_level.core() Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/EXPORTS.md Direct binding to argon2_ctx(). This function provides a direct binding to the `argon2_ctx()` function for advanced control. ```APIDOC ## Function: core ### Description Direct binding to `argon2_ctx()`. ### Reference `api-reference/low-level.md` ``` -------------------------------- ### Low-Level Hashing with Custom Salt Source: https://github.com/hynek/argon2-cffi/blob/main/_autodocs/index.md Perform low-level hashing using `hash_secret` with explicit control over salt, costs, and hash length. This is for advanced use cases. ```python import os from argon2.low_level import hash_secret, verify_secret, Type secret = b"password" salt = os.urandom(16) encoded_hash = hash_secret( secret=secret, salt=salt, time_cost=3, memory_cost=65536, parallelism=4, hash_len=32, type=Type.ID ) verify_secret(encoded_hash, secret, Type.ID) # Returns True ```