Skip to content

Instantly share code, notes, and snippets.

@ImanMousavi
Last active February 12, 2024 12:24
Show Gist options
  • Save ImanMousavi/7071a432068e6951e3b377970ec30f3b to your computer and use it in GitHub Desktop.
Save ImanMousavi/7071a432068e6951e3b377970ec30f3b to your computer and use it in GitHub Desktop.
Generate keystore file from raw private key
from web3 import Web3
from eth_account import Account
import json
import string
import random
# import qrcode
class bcolors:
HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKCYAN = "\033[96m"
OKGREEN = "\033[92m"
WARNING = "\033[93m"
FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
def password_generator(length):
"""Function that generates a password given a length"""
uppercase_loc = random.randint(1, 4) # random location of lowercase
symbol_loc = random.randint(5, 6) # random location of symbols
lowercase_loc = random.randint(7, 12) # random location of uppercase
password = "" # empty string for password
pool = string.ascii_letters + string.punctuation # the selection of characters used
for i in range(length):
if i == uppercase_loc: # this is to ensure there is at least one uppercase
password += random.choice(string.ascii_uppercase)
elif i == lowercase_loc: # this is to ensure there is at least one uppercase
password += random.choice(string.ascii_lowercase)
elif i == symbol_loc: # this is to ensure there is at least one symbol
password += random.choice(string.punctuation)
else: # adds a random character from pool
password += random.choice(pool)
return password # returns the string
w3 = Web3()
w3.eth.account.enable_unaudited_hdwallet_features()
acc, mnemonic = Account.create_with_mnemonic(num_words=24)
print(mnemonic)
password = password_generator(13)
print(f"🚀Private key :\n{bcolors.FAIL}{w3.to_hex(acc.key)}{bcolors.ENDC}")
print(f"\nAccount address :\n{bcolors.OKBLUE}{acc.address}{bcolors.ENDC}")
encrypted = Account.encrypt(w3.to_hex(acc.key), password)
encrypted_json = json.dumps(encrypted)
file_name = f"{acc.address}.json"
with open(file_name, "w") as file:
file.write(encrypted_json)
print(f"\n{bcolors.HEADER}🫣\tEncrypted account information has been saved to {file_name}.{bcolors.ENDC}")
print(f"\n{bcolors.HEADER}\tPassword file :{bcolors.ENDC}")
print(f"\n{bcolors.WARNING}\t{password}{bcolors.ENDC}\n")
# qr = qrcode.QRCode()
# qr.add_data(encrypted_json)
# qr.make()
# qr.print_ascii()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment