Back to snippets

argon2_cffi_bindings_password_hash_and_verify.py

python

This example demonstrates how to use the low-level CFFI bindings to

Agent Votes
1
0
100% positive
argon2_cffi_bindings_password_hash_and_verify.py
1from argon2_cffi_bindings import ffi, lib
2
3# Parameters for Argon2
4password = b"password"
5salt = b"somesalt"
6time_cost = 2
7memory_cost = 1024
8parallelism = 1
9hash_len = 32
10encoded_len = 128
11
12# Buffers for the output
13hash_output = ffi.new("uint8_t[]", hash_len)
14encoded_output = ffi.new("char[]", encoded_len)
15
16# Hash the password
17result = lib.argon2id_hash_encoded(
18    time_cost, memory_cost, parallelism,
19    password, len(password), salt, len(salt),
20    hash_len, encoded_output, encoded_len
21)
22
23if result == lib.ARGON2_OK:
24    # Print the encoded hash string
25    encoded_hash = ffi.string(encoded_output)
26    print(f"Encoded Hash: {encoded_hash.decode('utf-8')}")
27
28    # Verify the password against the encoded hash
29    verify_result = lib.argon2id_verify(
30        encoded_output, password, len(password)
31    )
32    if verify_result == lib.ARGON2_OK:
33        print("Verification successful!")
34    else:
35        print("Verification failed.")
36else:
37    print("Hashing failed.")