1

I am trying to encrypt sensible values in my environment file using a python script. I am using Fernet. I want to encrypt only those values which are not already encrypted, making sure that there isn't any multi-level encryption.

How can I know that a value is already encrypted or decrypted in this case?

Ayush Pallav
  • 919
  • 9
  • 18

1 Answers1

0

Simply attempt decryption with a TTL of None (the default). If it succeeds, then you don't need to do anything more. If it fails an InvalidToken exception will be raised which you can catch. Inside the except block you can then encrypt the file, as in the following example:

import base64
from pathlib import Path

from cryptography.fernet import Fernet, InvalidToken

key = Fernet.generate_key()
f = Fernet(key)
encrypted = f.encrypt(b'Hello world')

p1, p2 = Path('file1'), Path('file2')
p1.write_bytes(encrypted)
p2.write_bytes(base64.urlsafe_b64encode(b'\x80not encrypted'))

for example in (p1, p2):
    try:
        data = example.read_bytes()
        f.decrypt(data, None)
    except InvalidToken:
        example.write_bytes(f.encrypt(data))

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125