Skip to content

Instantly share code, notes, and snippets.

@orazdow
Last active March 14, 2023 19:25
Show Gist options
  • Save orazdow/520f9a831c5b80bef9779a21d735a696 to your computer and use it in GitHub Desktop.
Save orazdow/520f9a831c5b80bef9779a21d735a696 to your computer and use it in GitHub Desktop.
py aes encryption
#!/usr/bin/python3
import base64
import sys
from hashlib import sha256
from cryptography.fernet import Fernet, InvalidToken
def encrypt(pwd, st):
h = sha256(bytes(pwd, 'utf-8')).hexdigest()[:32]
key = base64.urlsafe_b64encode(bytes(h, 'utf-8'))
f = Fernet(key)
data = st if isinstance(st, bytes) else bytes(st, 'utf-8')
encrypted_bytes = f.encrypt(data)
print(encrypted_bytes.decode('utf-8'))
def decrypt(pwd, st):
try:
h = sha256(bytes(pwd, 'utf-8')).hexdigest()[:32]
key = base64.urlsafe_b64encode(bytes(h, 'utf-8'))
f = Fernet(key)
data = st if isinstance(st, bytes) else bytes(st, 'utf-8')
decrypted_bytes = f.decrypt(data)
print(decrypted_bytes.decode('utf-8'))
except InvalidToken:
print('invalid pass token')
def encryptFromFile(pwd, path):
try:
with open(path, 'rb') as file:
encrypt(pwd, file.read())
except FileNotFoundError:
print('file not found:', path)
def decryptFromFile(pwd, path):
try:
with open(path, 'rb') as file:
decrypt(pwd, file.read())
except FileNotFoundError:
print('file not found:', path)
if __name__ == '__main__':
args = sys.argv[1:]
if len(args) == 0 or len(args) < 3 and args[0] != '-h':
print('not enough arguments -h for help')
sys.exit(0)
if args[0] == '-e':
encrypt(args[1], args[2])
elif args[0] == '-d':
decrypt(args[1], args[2])
elif args[0] == '-ef':
encryptFromFile(args[1], args[2])
elif args[0] == '-df':
decryptFromFile(args[1], args[2])
elif args[0] == '-h':
print("""crypt -e pwd str : encrypt string (stdin > stdout)
crypt -f pwd str : decrypt string (stdin > stdout)
crypt -ef pwd path : encrypt from file (file > stdout)
crypt -df pwd path : decrypt from file (file > stdout)""")
else:
print('invalid argument(s) -h for help')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment