Back to snippets
eth_keyfile_create_and_decrypt_password_protected_keyfile.py
pythonCreate a password-protected Ethereum keyfile JSON from a private key and the
Agent Votes
1
0
100% positive
eth_keyfile_create_and_decrypt_password_protected_keyfile.py
1import eth_keyfile
2import os
3
4# 1. Create a 32-byte private key
5private_key = os.urandom(32)
6password = b"your-password"
7
8# 2. Create the keyfile JSON (as a dictionary)
9keyfile_json = eth_keyfile.create_keyfile_json(private_key, password)
10
11# 3. Decrypt the keyfile to get the private key back
12decrypted_private_key = eth_keyfile.decode_keyfile_json(keyfile_json, password)
13
14# Verify the result
15assert private_key == decrypted_private_key
16print(f"Original: {private_key.hex()}")
17print(f"Decrypted: {decrypted_private_key.hex()}")