pythonpython-3.xbytepynacl

How to use the PyNaCl secret key generated as environnement variable


I am generating secret key using PyNaCl:

nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)

The keys look like:

b'\xa5\x8bL\xc4\xc0\xe6\xe3\xe5#\xb4{)\xd7uO(\xb11\x85\x88N\xfd\xf6>\nC\xb5\x95\\\xf1\x8b\xe8'

They are 32 bytes long and must stay 32 bytes long, how can I use them as environment variable?

EDIT:

I have try the following:

my_key = SecureMessage.generate #  b'\xe1\xd1\xef\x8anx\xb5\xf1n\xa8N/w\x90\xaejG\xdaN\x97\xbc\xb2\x90&\xedB\xa9\xf3/8\xa4?'
my_key_as_hex = my_key.hex() # e1d1ef8a6e78b5f16ea84e2f7790ae6a47da4e97bcb29026ed42a9f32f38a43f
my_key = bytes(my_key_as_hex, "utf-8") # b'e1d1ef8a6e78b5f16ea84e2f7790ae6a47da4e97bcb29026ed42a9f32f38a43f'

Solution

  • Here is how to go about it.

    Generate your Key

    key = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)
    

    At this point the key is in bytes format:

    b"T\x93\xacsg'\xb4\x93\xc2+.\x8a\xe0\x8f\xd7\x8eCi\xd0\xd7\xb0\xa1\xdeX\x93\x05\xa2\xb6\xf6\x82`%"
    

    As adviced in the comments, convert it to hexadecimal

    hexed_key = key.hex()
    

    That should give you something like:

    5493ac736727b493c22b2e8ae08fd78e4369d0d7b0a1de589305a2b6f6826025
    

    Store the above value in your environment variables. When it comes to time to use your secret key, just convert it back.

    hexed_key = os.environ.get('HEXED_KEY', '')
    box = nacl.secret.SecretBox(bytes.fromhex(hexed_key))
    

    The part to note in the last line is bytes.fromhex(hexed_key) which will convert your hexadecimal into bytes

    Your box is now ready to use...