Created
October 30, 2022 18:24
-
-
Save xtekky/7d95d223364c0b0545d3e680fa38de3d to your computer and use it in GitHub Desktop.
Python decrypt/encrypt aes with iv
This file contains 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
import base64 | |
import hashlib | |
from Crypto.Cipher import AES | |
class Aes(object): | |
def __init__(self, key: str, iv: str): | |
self.bs = AES.block_size | |
self.key = hashlib.sha256(key.encode()).digest() | |
self.iv = iv.encode() | |
def encrypt(self, raw): | |
return base64.b64encode( | |
AES.new(self.key, AES.MODE_CBC, self.iv).encrypt( | |
self._pad_pkcs7(raw).encode() | |
) | |
) | |
def decrypt(self, enc: str or bytes): | |
if not isinstance(enc, (bytes, bytearray)): | |
enc = enc.encode() | |
return self._unpad_pkcs7( | |
AES.new(self.key, AES.MODE_CBC, self.iv).decrypt(base64.b64decode(enc)) | |
) | |
def _pad_pkcs7(self, source): | |
return source + chr(AES.block_size - len(source) % AES.block_size) * ( | |
AES.block_size - len(source) % AES.block_size | |
) | |
def _unpad_pkcs7(self, source): | |
return source[0 : len(source) - source[len(source) - 1]] | |
if __name__ == "__main__": | |
iv = "1234567890123456" # needs to be 16 bytes/chars long | |
key = "key" | |
text = "Hello World" | |
encrypted = Aes(key, iv).encrypt(text) | |
print('Encrypted:', encrypted) | |
decrypted = Aes(key, iv).decrypt(encrypted.decode()) # encrypted string can be str or bytes (there is safety check) | |
print('Decrypted:', decrypted.decode()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment