Python – How to Store Private Key as an Environmental Variable and Use It in Code

command-lineprivate-keypy-solc-xpython

import os
from dotenv import dotenv_value
.
.
.

private_key = os.getenv("PRIVATE_KEY")
.
.
print(private_key) //for testing purposes only

This is what I currently have to utilize my private key in my smart contract. I do not want it visible in the code for obvious purposes, but I do not know how I can do this on Windows. I know that on Mac it is much more simple to do. I may have stored as an environmental variable incorrectly, but I do not think that is the case. I do not know if using os or getenv is the wrong place to start or what. I need some help on this.

    INFO: Could not find files for the given pattern(s).
None
Traceback (most recent call last):
  File "C:\Users\amazi\demos\web3_py_simple_storage\deploy.py", line 58, in <module>
    signed_txn = w3.eth.account.sign_transaction(transaction, private_key=private_key)
  File "C:\Python310\lib\site-packages\eth_utils\decorators.py", line 18, in _wrapper
    return self.method(obj, *args, **kwargs)
  File "C:\Python310\lib\site-packages\eth_account\account.py", line 728, in sign_transaction
    account = self.from_key(private_key)
  File "C:\Python310\lib\site-packages\eth_utils\decorators.py", line 18, in _wrapper
    return self.method(obj, *args, **kwargs)
  File "C:\Python310\lib\site-packages\eth_account\account.py", line 250, in from_key
    key = self._parsePrivateKey(private_key)
  File "C:\Python310\lib\site-packages\eth_utils\decorators.py", line 18, in _wrapper
    return self.method(obj, *args, **kwargs)
  File "C:\Python310\lib\site-packages\eth_account\account.py", line 775, in _parsePrivateKey
    return self._keys.PrivateKey(HexBytes(key))
  File "C:\Python310\lib\site-packages\hexbytes\main.py", line 23, in __new__     
    bytesval = to_bytes(val)
  File "C:\Python310\lib\site-packages\hexbytes\_utils.py", line 30, in to_bytes  
    raise TypeError(f"Cannot convert {val!r} of type {type(val)} to bytes")       
TypeError: Cannot convert None of type <class 'NoneType'> to bytes

This is the error that I get after making the adjustments that you suggested. I very well could have messed up setting up the path within the file. I am still very new to this, and I do not have much experience with python.

Best Answer

Good Day One Will Do the Following

import os

private_key = os.environ.get('PRIVATE_KEY')

remember to include the following if this is a Django Project in the settings.py

from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

and also use a .gitignore file and exclude your .env file

I hope This Answers your Question

Thank You

Related Topic