[python]Encrypt password to a file and decrypt it from file

Here’s a sample code which I am trying, I intend to encrypt the credential when used by automation script. Here’s is the sample.
1. getpass will obfuscate user’s password input on the screen, however it is visible on the pycharm console.
2. cryptography.Fernet is the module which does key generation, encrypt and decrypt. The encrypt and decrypt takes in byte stream…
3. Need to convert the password from string to bytes, the encode method uses ‘utf-8’ encoder to convert the string to byte.
4. Decrypt the contents of the file, remember to decode it back otherwise the password is still in byte data type which your appliance or server might not recognize and reject your credential.

from getpass import getpass as GP
from cryptography.fernet import Fernet


credential = {'username': None,
              'password': None}

credential['username'] = input("Enter your username: ")
password = GP("Enter your password: ")
# utf-8 encoded bytes
password_byte = password.encode('utf-8')
key = Fernet.generate_key()
cipher = Fernet(key)
token = cipher.encrypt(password_byte)
with open("password.txt", "wb") as file:
    file.write(token)

with open("password.txt", "rb") as file:
    token1 = file.read()

credential['password'] = cipher.decrypt(token1).decode('utf-8')
print(credential['password'])
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s