Skip to content

Instantly share code, notes, and snippets.

@DavidEdwards
Created April 8, 2019 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidEdwards/3b3312470f00cc83fe869d8bd5aae515 to your computer and use it in GitHub Desktop.
Save DavidEdwards/3b3312470f00cc83fe869d8bd5aae515 to your computer and use it in GitHub Desktop.
Convert a JSON formatted encrypted private key into a raw unencrypted private key (with options for testing against multiple passwords)
import hashlib
from Crypto.Hash import keccak
import codecs
from Crypto.Cipher import AES
from Crypto.Util import Counter
pws = [ "password1", "password2" ]
cipher = "0000000000000000000000000000000000000000000000000000000000000001"
salt = "0000000000000000000000000000000000000000000000000000000000000001"
iv = "00000000000000000000000000000001"
mac = "0000000000000000000000000000000000000000000000000000000000000001"
print("Testing with: "+str(len(pws))+" passwords...")
for pw in pws:
print("-----")
print("Password: "+pw)
dec_key = hashlib.scrypt(bytes(pw, 'utf-8'), salt=bytes.fromhex(salt), n=262144, r=8, p=1, maxmem=2000000000, dklen=32)
print("Decoded key: "+str(dec_key))
validate = dec_key[16:] + bytes.fromhex(cipher)
keccak_hash=keccak.new(digest_bits=256)
keccak_hash.update(validate)
print("Computed Mac: "+keccak_hash.hexdigest())
print(" Mac: "+mac)
if keccak_hash.hexdigest() == mac:
iv_int=int(iv, 16)
ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)
dec_suite = AES.new(dec_key[:16], AES.MODE_CTR, counter=ctr)
plain_key = dec_suite.decrypt(bytes.fromhex(cipher))
print("Key bytes: "+str(plain_key))
print("Key encoded: "+codecs.encode(plain_key, "hex").decode("ascii"))
else:
print("Computed mac is not the same as the given mac. The password or ciphertext are likely incorrectly entered.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment