SoftHSMv2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# This script derives the masterKey and tokenKey from a SoftHSMv2 token. | |
# For more details: https://xakcop.com/post/softhsmv2/ | |
import sys | |
from Cryptodome.Hash import SHA256 | |
from Cryptodome.Cipher import AES | |
from Cryptodome.Util.Padding import unpad | |
PBE_ITERATION_BASE_COUNT = 1500 | |
def kdf(salt, pin): | |
h = SHA256.new() | |
h.update(salt) | |
h.update(pin) | |
tmp = h.digest() | |
iter = PBE_ITERATION_BASE_COUNT + salt[-1] | |
for _ in range(iter-1): | |
h = SHA256.new() | |
h.update(tmp) | |
tmp = h.digest() | |
return tmp | |
def decrypt(master_key, iv, blob): | |
cipher = AES.new(master_key, mode=AES.MODE_CBC, iv=iv) | |
data = cipher.decrypt(blob) | |
data = unpad(data, 16) | |
if data[0:3] != b'RJR': | |
print("Incorrect magic") | |
return None | |
return data[3:] | |
if __name__ == '__main__': | |
if len(sys.argv) < 3: | |
print("Usage: {} <pin> <salt> [iv] [blob]".format(sys.argv[0])) | |
sys.exit(1) | |
pin = sys.argv[1].encode('ascii') | |
salt = bytes.fromhex(sys.argv[2]) | |
master_key = kdf(salt, pin) | |
print("masterKey: {}".format(master_key.hex())) | |
if len(sys.argv) == 5: | |
iv = bytes.fromhex(sys.argv[3]) | |
blob = bytes.fromhex(sys.argv[4]) | |
key = decrypt(master_key, iv, blob) | |
print("tokenKey: {}".format(key.hex())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment