Hazmat PBFDK2PBKDF2 (Password-Based Key Derivation Function 2) is defined in RFC 2898 and generates a salted hash. Often this is used to create an encryption key from a defined password, and where it is not possible to reverse the password from the hashed value. It is used in TrueCrypt to generate the key required to read the header information of the encrypted drive, and which stores the encryption keys. Also, it is used in WPA-2 in order to create a hashed version of the password. With this, WPA-2 uses 4,096 interations. We can also specify the length of the generated hashed. |
Code
The code is:
import os import sys import base64 from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC round=1000 hashtype=0 length=32 message="Hello" if (len(sys.argv)>1): message=str(sys.argv[1]) if (len(sys.argv)>2): hashtype=int(sys.argv[2]) if (len(sys.argv)>3): round=int(sys.argv[3]) if (len(sys.argv)>4): length=int(sys.argv[4]) salt = os.urandom(16) h=None if (hashtype==0): h=hashes.SHA1() elif (hashtype==1): h=hashes.SHA512_224() elif (hashtype==2): h=hashes.SHA512_256() elif (hashtype==3): h=hashes.SHA224() elif (hashtype==4): h=hashes.SHA256() elif (hashtype==5): h=hashes.SHA384() elif (hashtype==6): h=hashes.SHA512() elif (hashtype==7): h=hashes.SHA3_224() elif (hashtype==8): h=hashes.SHA3_256() elif (hashtype==9): h=hashes.SHA3_384() elif (hashtype==10): h=hashes.SHA3_512() elif (hashtype==11): h=hashes.MD5() elif (hashtype==12): h=hashes.SM3() elif (hashtype==13): h=hashes.BLAKE2b(64) elif (hashtype==14): h=hashes.BLAKE2s(32) kdf = PBKDF2HMAC(algorithm=h,length=length,salt=salt, iterations=round) key = kdf.derive(message.encode()) # verify kdf = PBKDF2HMAC(algorithm=h, length=length,salt=salt, iterations=round) rtn=kdf.verify(message.encode(), key) print(f"Message:\t{message}") print(f"Salt:\t\t{salt.hex()}") print(f"Salt:\t\t{base64.b64encode(salt).decode()}") print(f"Rounds:\t\t{round}") print(f"Hash:\t\t{kdf._algorithm.name}") print(f"\nKey:\t\t{key.hex()}") print(f"Key:\t\t{base64.b64encode(key).decode()}") if (rtn==None): print("KDF Verified")
and a sample run:
Message: Hello Salt: 44c4eff6b89c09d463051dbb7399275e Salt: RMTv9ricCdRjBR27c5knXg== Rounds: 4096 Hash: sha384 Key: aa6414720af8de96ed62245c43f7098dcb3a30d0ae9edbf9c51d9958735820fc Key: qmQUcgr43pbtYiRcQ/cJjcs6MNCuntv5xR2ZWHNYIPw= KDF Verified