#!/usr/bin/env python
import os
import binascii
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
backend = default_backend()
salt = b"324d9e95"
# salt will be 8 bytes, each character means a byte:
# 00000011 00000010 00000100 00001101 00001001 00001110 00001001 00000101
# In the case of binascii.unhexlify(salt), salt will be 4 bytes, two characters meas a byte:
# ==> 32 -> '2', 4d -> 'M', 9e -> '\x9e' 95 -> '\x95'
# ==> b'2M\x9e\x95'
# ==> 00000010 01001110 10011110 10010101
salt = b"\x8d\x3d\x71\xd6\x1f\x47\xa9\x2d"
# salt will be 8 bytes, each \xnn means a byte:
# 10001101 00111101 01110001 11010110 00011111 01000111 10101001 00101101
# In this situation, we can use binascii.unhexlify() to covert hex string to binary array:
# salt = binascii.unhexlify("8d3d71d61f47a92d")
password = b"123456"
# This is the same as:
# password = b"\x31\x32\x33\x34\x35\x36"
print(binascii.hexlify(salt))
print(binascii.hexlify(password))
# derive
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
backend=backend
)
key = kdf.derive(password)
# This is the same as printf("%02x" data[i]) in c programming language.
print(binascii.hexlify(key))