Last active
December 21, 2018 07:37
-
-
Save vincentwyshan/1ca98a58b69dcf733b1018907368226a to your computer and use it in GitHub Desktop.
AES Cipher with PyCryptodome
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ python3.6+ """ | |
| from hashlib import md5 | |
| from base64 import b64decode | |
| from base64 import b64encode | |
| from Crypto.Cipher import AES | |
| from typing import ByteString | |
| BLOCK_SIZE = 32 | |
| pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \ | |
| chr(BLOCK_SIZE - len(s) % BLOCK_SIZE).encode("utf8") | |
| unpad = lambda s: s[:-ord(s[len(s) - 1:])] | |
| class AESCipher: | |
| """ | |
| >>> e = AESCipher("secret key") | |
| >>> s = e.encrypt(b"test") | |
| >>> isinstance(s, bytes) | |
| True | |
| >>> e.decrypt(s) == b"test" | |
| True | |
| """ | |
| def __init__(self, key: str): | |
| key = md5(key.encode('utf8')).hexdigest() | |
| self.key = key.encode("utf8") | |
| def encrypt(self, raw: ByteString) -> ByteString: | |
| assert isinstance(raw, bytes) | |
| raw = pad(raw) | |
| cipher = AES.new(self.key, AES.MODE_ECB) | |
| return b64encode(cipher.encrypt(raw)) | |
| def decrypt(self, enc: ByteString) -> ByteString: | |
| assert isinstance(enc, bytes) | |
| enc = b64decode(enc) | |
| cipher = AES.new(self.key, AES.MODE_ECB) | |
| return unpad(cipher.decrypt(enc)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment