Skip to content

Instantly share code, notes, and snippets.

@jrelo
Forked from tryone144/aes.py
Created August 27, 2018 20:35
Show Gist options
  • Save jrelo/e46ece474b104ecf61b01d942615c034 to your computer and use it in GitHub Desktop.
Save jrelo/e46ece474b104ecf61b01d942615c034 to your computer and use it in GitHub Desktop.
Implementation of AES as used by https://aesencryption.net
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# implementation of AES as used by https://aesencryption.net
#
# (c) 2018 Bernd Busse
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers.algorithms import AES
from cryptography.hazmat.primitives.ciphers.modes import CBC
from cryptography.hazmat.backends import default_backend
import base64
import sys
AES_IV = b'\x31\x32\x33\x34\x35\x36\x37\x38\x62\x30\x7a\x32\x33\x34\x35\x6e'
class EncryptionError(RuntimeError):
pass
class DecryptionError(RuntimeError):
pass
def usage(executable):
sys.stderr.write("usage: {} -e KEY KEYSIZE TEXT\n".format(executable))
sys.stderr.write(" {} -d KEY KEYSIZE CIPHER\n".format(executable))
sys.stderr.flush()
def encrypt(password, message, keysize=128):
if keysize not in (128, 192, 256):
raise EncryptionError(
"Invalid key size: {} must be one of (128, 192, 256)"
.format(keysize))
aes_key = (password + '\0' * ((keysize // 8) - len(password))).encode("utf-8")
cipher = Cipher(algorithm=AES(aes_key[:(keysize // 8)]),
mode=CBC(AES_IV),
backend=default_backend())
cipher = cipher.encryptor()
count = 16 - (len(message) % 16)
c_text =cipher.update(message.encode("utf-8")) + cipher.update(count * bytes([count])) + cipher.finalize()
return base64.b64encode(c_text).decode("utf-8")
def decrypt(password, ciphertext, keysize=128):
if keysize not in (128, 192, 256):
raise DecryptionError(
"Invalid key size: {} must be one of (128, 192, 256)"
.format(keysize))
aes_key = (password + '\0' * ((keysize // 8) - len(password))).encode("utf-8")
cipher = Cipher(algorithm=AES(aes_key[:(keysize // 8)]),
mode=CBC(AES_IV),
backend=default_backend())
cipher = cipher.decryptor()
message = cipher.update(base64.b64decode(ciphertext)) + cipher.finalize()
message = message[:-message[-1]]
return message.decode("utf-8")
if __name__ == "__main__":
if len(sys.argv) != 5:
usage(sys.argv[0])
exit(1)
if sys.argv[1] == "-e":
# Run encryption
cipher = encrypt(sys.argv[2], sys.argv[4], keysize=sys.argv[3])
print("Ciphertext: {:s}".format(cipher))
elif sys.argv[1] == "-d":
# Run decryption
plain = decrypt(sys.argv[2], sys.argv[4], keysize=sys.argv[3])
print("Plaintext: {:s}".format(plain))
else:
usage(sys.argv[0])
exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment