How to Encrypt and Decrypt application password using Python

# Description: This program will be executed only when we have a new password file.

from cryptography.fernet import Fernet
import os

### 1. read your password file
with open('pwd.txt') as f:
mypwd = ''.join(f.readlines())

### 2. generate key and write it in a file
key = Fernet.generate_key()
f = open("refKey.txt", "wb")

### 3. encrypt the password and write it in a file
refKey = Fernet(key)
mypwdbyt = bytes(mypwd, 'utf-8') # convert into byte
encryptedPWD = refKey.encrypt(mypwdbyt)
f = open("encryptedPWD.txt", "wb")
### 4. delete the password file
if os.path.exists("pwd.txt"):
print("File is not available")
# Description: This program will read the key and encrypted pwd generated by GenerateEncryptedKey program. Can be executed multiple time.
from cryptography.fernet import Fernet

# read encrypted pwd and convert into byte
with open('encryptedPWD.txt') as f:
encpwd = ''.join(f.readlines())
encpwdbyt = bytes(encpwd, 'utf-8')

# read key and convert into byte
with open('refKey.txt') as f:
refKey = ''.join(f.readlines())
refKeybyt = bytes(refKey, 'utf-8')

# use the key and encrypt pwd
keytouse = Fernet(refKeybyt)
myPass = (keytouse.decrypt(encpwdbyt))
print("my password - ",myPass)



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store