In Smart Contract development, the most common (and costly) mistake is leaving private keys in plaintext within .env files or directly in the code. If accidentally pushed to GitHub, your funds will disappear in seconds.

The professional solution is to use a Keystore JSON: an encrypted file that protects your key with a password. This guide explains how to create a Keystore manager using Python.

Project Setup

We will use uv, the fastest Python package manager, and the official Ethereum Foundation library.

  1. Initialize the project: uv init keystore_manager
  2. Install dependencies: uv add eth-account
  3. Create the file: touch manager.py

The Code: Keystore Manager

The script prompts for your private key and a password to generate an encrypted file.

import getpass import json from eth_account import Account def main(): print("/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/") print("/* KEYSTORE MANAGER */") print("/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/") private_key = getpass.getpass("\n Enter your private key: ") password = getpass.getpass("\n Enter a password: ") password_confirm = getpass.getpass("Confirm your password: ") if password != password_confirm: print("\n ---ERROR \nPasswords do not match") return loaded_account = Account.from_key(private_key) json_key_store = loaded_account.encrypt(password=password) with open("account.keystore.json", "w") as fp: json.dump(json_key_store, fp) print("\n Keystore created successfully") return if __name__ == "__main__": main() 

Key Security Points

  • getpass: Essential for terminal scripts. It prevents your private key or password from appearing in console history or being visible to onlookers.
  • Account.encrypt: Uses the Ethereum encryption standard. This generates a file that can only be decrypted with the correct password.
  • .gitignore: Even if encrypted, never upload these files to public repositories. Add *.json or your specific keystore filename to your .gitignore.

Usage

To run your manager, execute:
uv run manager.py

Once the account.keystore.json file is generated, you can securely use it in your deployment scripts with Titanoboa, Ape, or Foundry.