Symmetric
Data is encoded and decoded with the
same key.

from cryptography.fernet import Fernet
key = Fernet.generate_key()
obj = Fernet(key)
msg = "password_123"
encrypted = obj.encrypt(msg.encode())
decrypted = obj.decrypt(encrypted).decode()
print(encrypted)
print(decrypted)
Asymmetric
Two keys, a public key and a
private key.

import rsa
publicKey, privateKey = rsa.newkeys(512)
msg = "password_123"
encrypted = rsa.encrypt(msg.encode(), publicKey)
decrypted = rsa.decrypt(encrypted, privateKey).decode()
print(encrypted)
print(decrypted)
Applications (2)
Encrypt / decrypt password using restricted
private key .pem file.

import rsa, os
publicKey, privateKey = rsa.newkeys(512)
DIR = os.path.dirname(os.path.realpath(__file__))
with open(DIR + '/../public.pem', 'wb') as p:
p.write(publicKey.save_pkcs1('PEM'))
with open(DIR + '/private.pem', 'wb') as p:
p.write(privateKey.save_pkcs1('PEM'))
print(publicKey)
print(privateKey)

import rsa, os
msg = "password_123555"
DIR = os.path.dirname(os.path.realpath(__file__))
with open(DIR + '/public.pem', 'rb') as p:
publicKey = rsa.PublicKey.load_pkcs1(p.read())
with open(DIR + '/encrypted.txt', 'wb') as f:
encrypted = rsa.encrypt(msg.encode(), publicKey)
f.write(encrypted)
print(encrypted)

import rsa, os
DIR = os.path.dirname(os.path.realpath(__file__))
with open(DIR + '/../encrypted.txt', "rb") as f:
encrypted = f.read()
with open(DIR + '/private.pem', "rb") as p:
privateKey = rsa.PrivateKey.load_pkcs1(p.read())
decrypted = rsa.decrypt(encrypted, privateKey).decode()
print(encrypted)
print(privateKey)
print(decrypted)
App with
cmd arguments to encrypt / decrpyt password

import sys, rsa
if len(sys.argv) < 2:
sys.exit("Too few arguments")
action = sys.argv[1]
if action == 'encrypt':
msg = sys.argv[2]
with open('./public.pem', 'rb') as p:
publicKey = rsa.PublicKey.load_pkcs1(p.read())
with open('./password.bin', 'wb') as f:
encrypted = rsa.encrypt(msg.encode(), publicKey)
f.write(encrypted)
print(encrypted)
if action == 'decrypt':
master_pass = sys.argv[2]
if master_pass != 'master_pass':
sys.exit('Wrong master password')
with open('./password.bin', "rb") as f:
encrypted = f.read()
with open('./restricted/private.pem', "rb") as p:
privateKey = rsa.PrivateKey.load_pkcs1(p.read())
decrypted = rsa.decrypt(encrypted, privateKey).decode()
print(decrypted)