encryption

decrypt

edotenv.encryption.decrypt(target, key, decode=True, encoding='utf8')[source]

Decrypt a string.

Parameters
  • target (str or bytes) – The string to decrypt.

  • key (str) – The key used to decrypt the string.

  • decode (bool) – Whether to decode the target from bytes after decryption or not.

  • encoding (str) – Encoding used to decode the target from bytes if decode is True.

Returns

The decrypted string.

Return type

str

Example

from edotenv.encryption import *

# Encrypt string
key = gen_key()
target = 'Encryption time!'
encrypted = encrypt(target, key)
print('encrypted: ' + str(encrypted))

# Decrypt string
decrypted = decrypt(encrypted, key)
print('decrypted: ' + decrypted)
encrypted: b'gAAAAABiLA42WGZXr0z-wiph8RCPyqA2SCyDPu_fH_2zBiYBKgHM0vQ01lRmyRASyqGeP1j-r_6a11wz8rtj1mA4Vq0JUA1pFwyOQaGY1i77NByYBM7jNSA='
decrypted: Encryption time!

encrypt

edotenv.encryption.encrypt(target, key, to_bytes=True, encoding='utf8')[source]

Encrypt a string.

Parameters
  • target (str or bytes) – The string to encrypt.

  • key (str) – The key used to encrypt the string.

  • to_bytes (bool) – Whether to convert the target to bytes before encryption or not.

  • encoding (str) – Encoding used to convert the target to bytes if to_bytes is True.

Returns

The encrypted string as bytes.

Return type

bytes

Example

from edotenv.encryption import encrypt

key = gen_key()
target = 'Encryption time!'
encrypted = encrypt(target, key)
print(encrypted)
b'gAAAAABiLA42eg5luL4t65YczowBmJAAblTBOXf2xnRY_LcKKz2eeCO-x7u-YjTx6wWxfzSezqfUPGSEqzulfu2heM-zNE4clSPkwzHZE0pZztGUKP4FRCc='

gen_key

edotenv.encryption.gen_key()[source]

Generate a key for encryption and decryption.

Returns

Key for encrypting and decrypting.

Return type

bytes

Example

from edotenv.encryption import gen_key

key = gen_key()
print(key)
b'1PIoNPSUSijMixzkcjBrxbHk3HW9lHdYWm2w4cXip_I='

read_key_file

edotenv.encryption.read_key_file(key_path=None, create_if_not_exists=True)[source]

Read a key file or create one if it does not exist.

Parameters
  • key_path (str or None) –

    The path to the key used to encrypt and decrypt the .env file.

    • If the file does not exist, then a key file will be automatically generated

    • If None, defaults to a file inside the package’s directory

  • create_if_not_exists (bool) – Whether to generate a new key and create the key file if it does not exist.

Returns

Key for encrypting and decrypting from the key file.

Return type

bytes

Example

import tempfile

from edotenv.encryption import read_key_file

with tempfile.TemporaryDirectory() as folder:
    key_path = f'{folder}/.env.key'
    key = read_key_file(key_path)
    print(key)
b'hrPAtnzhxEfQ1J2jQX6L8Yv6ZDZbLhXajoLwn2AAxQs='