DEV Community

Cover image for Web3 Security: How to Protect Your Private Key using Python
Rafael Abuawad
Rafael Abuawad

Posted on Originally published at x.com

Web3 Security: How to Protect Your Private Key using Python

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()
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
anh_nguynvn_0478e614ba profile image
Anh Nguyễn Văn •

Việc lưu private key trực tiếp trong code là một sai lầm cực kỳ phổ biến, nhất là khi anh em mới làm quen với Web3. Một kinh nghiệm xương máu mình rút ra là dù có dùng thư viện Python để mã hóa thì việc quản lý biến môi trường (environment variables) vẫn rất rủi ro nếu vô tình đẩy file .env lên GitHub. Thay vì chỉ tập trung vào việc viết code mã hóa, mình thấy việc sử dụng các giải pháp chuyên dụng như HashiCorp Vault hoặc các dịch vụ KMS của cloud provider sẽ an toàn hơn nhiều cho môi trường production. Cách tiếp cận này giúp tách biệt hoàn toàn logic xử lý và dữ liệu nhạy cảm, giảm thiểu tối đa rủi ro khi bị lộ source code.