# PBKDF2

PBKDF2 is a key derivation function in cryptography, originally defined in version 2.0 of the PKCS#5 standard in RFC2898. It’s used for reducing vulnerabilities to brute force attacks.

### Algorithm Format <a href="#algorithm-format" id="algorithm-format"></a>

```shellscript
# Algorithm
pbkdf2$<iteration>$<salt-length>

# e.g.
pbkdf2$10000$50
```

### PBKDF2-HMAC-SHA256 <a href="#pbkdf2-hmac-sha256" id="pbkdf2-hmac-sha256"></a>

PBKDF2 is part of PKCS#5 v2.0. The format is as follows:

```shellscript
sha256:<iteration>:<base64-salt>:<base64-password-hash>

# ex.
sha256:10000:ayZoqdmIewDpUB:Ud6aAhvpw9RqZPt/0Rd0U9uPDKLOWKnYHAS+Lm07oqDWwDLw/U74P0jXQ0nsGW9O/jc=
```

To create the hash based on this, run the following commands.

```
echo 'sha256:10000:'$(echo '<salt-string>' | base64 | cut -c 1-14)':'$(echo 'password-string' | base64) > hash.txt
```

Now crack the hash using Hashcat.

```
hashcat -m 10900 hash.txt wordlist.txt
```

### Using PBKDF2 in Python <a href="#using-pbkdf2-in-python" id="using-pbkdf2-in-python"></a>

Reference: [Pycryptodome Official Docs](https://pycryptodome.readthedocs.io/en/latest/src/protocol/kdf.html#pbkdf2)

We can use PBKDF2 easily thanks of **Pycryptodome**.\
We need to install it first.

```
pip install pycryptodome
```

Below is a Python script to derive keys from a password with PBKDF2.

```shellscript
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Hash import SHA512
from Crypto.Random import get_random_bytes

password = b'secret'
salt = get_random_bytes(16)
keys = PBKDF2(password, salt, 64, count=1000000, hmac_hash_module=SHA512)
key1 = keys[:32]
key2 = keys[32:]
print(f"key1: {key1.hex()}")
print(f"key2: {key2.hex()}")
```
