ethereum / eth-keys

A common API for Ethereum key operations.
MIT License
159 stars 64 forks source link

Importing and Exporting keys #78

Closed wojake closed 2 years ago

wojake commented 2 years ago

What was wrong?

I've tried to debug my code for hours using different random methods that I could think of. I'm trying to export my keys to a file (txt for now) and import it for later use. Here's my code:

import eth_keys
import os

def generate_keys():
    Priv = eth_keys.keys.PrivateKey(os.urandom(32))
    Pub = Priv.public_key

    msg = b'Sign Me 321'

    signature = Priv.sign_msg(msg)
    recoveredPubKey = signature.recover_public_key_from_msg(msg)

    if recoveredPubKey == Pub:
        valid = Pub.verify_msg(msg, signature)
        if valid:
            with open(r"C:\net\public.txt", "w") as f:
                f.write(Pub.__str__())

            with open(r"C:\net\private.txt", "w") as f:
                f.write(Priv.__str__())

def sign(message):
    """
        Signs a message using the private.txt, returns (Signed Message)
    """

    with open(r"C:\net\private.txt") as f:
        eth_keys.keys.PrivateKey(private_key_bytes=f.read())

    signature = eth_keys.keys.PrivateKey.sign_msg(message=bytes(message))
    verification = eth_keys.keys.PrivateKey.public_key.verify_msg(message=message, signature=signature)

    if verification is True:
        return signature

    else:
        assert verification is not False, \
            "Try again or contact support, public key and private key did not correlate in sign()"

generate_keys()
sign("Hello")

How can it be fixed?

Well, I just want to export and import my keys without an error popping up. It would also be nice if you could tell me which file type is better to use to store private keys.

pipermerriam commented 2 years ago

You can use this: https://github.com/ethereum/eth-keyfile