Skip to content

Instantly share code, notes, and snippets.

@ptisserand
Created May 2, 2022 18:16
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 ptisserand/d71aab6f4babb6545ca414dc27b75acd to your computer and use it in GitHub Desktop.
Save ptisserand/d71aab6f4babb6545ca414dc27b75acd to your computer and use it in GitHub Desktop.
Extract private key from Terra Station Wallet export
#!/usr/bin/env python
#
# Extract private key from Terra Station Wallet exported private key
#
# python ./extract_private.py "DATA FROM 'Export Wallet' - 'Private Key'" "your password"
#
# Your private key base64 encoded will be print on stdout
#
import sys
import json
from base64 import b64decode, b64encode
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import padding
def decrypt_key(*, key: bytes, iv: bytes, ciphered: bytes) -> bytes:
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
d = cipher.decryptor()
padded = d.update(ciphered) + d.finalize()
# remove padding
unpadder = padding.PKCS7(128).unpadder()
plain = unpadder.update(padded) + unpadder.finalize()
plain = plain.decode("utf-8")
return bytes.fromhex(plain)
def derive_key(*, password: str, salt: bytes) -> bytes:
kdf = PBKDF2HMAC(algorithm=hashes.SHA1(), length=32, salt=salt, iterations=100)
key = kdf.derive(password.encode("utf-8"))
return key
def parse_encrypted_key(message: str):
salt = bytes.fromhex(message[:32])
iv = bytes.fromhex(message[32:64])
ciphered = b64decode(message[64:])
return {
"salt": salt,
"iv": iv,
"ciphered": ciphered
}
def extract_encrypted_key(message: str):
message = b64decode(message)
data = json.loads(message)
return data["encrypted_key"]
def get_key(*, message: str, password: str) -> str:
encrypted_key = extract_encrypted_key(message)
data = parse_encrypted_key(encrypted_key)
kek = derive_key(password=password, salt=data["salt"])
key = decrypt_key(key=kek, iv=data["iv"], ciphered=data["ciphered"])
return b64encode(key).decode("utf-8")
if __name__ == "__main__":
message = sys.argv[1]
password = sys.argv[2]
output = get_key(message=message, password=password)
print(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment