Skip to content

Instantly share code, notes, and snippets.

@jdgoettsch
Last active April 12, 2023 22:44
Show Gist options
  • Save jdgoettsch/0443668071be15c6dc9fa95f702e3120 to your computer and use it in GitHub Desktop.
Save jdgoettsch/0443668071be15c6dc9fa95f702e3120 to your computer and use it in GitHub Desktop.
python encryption/decryption class
from __future__ import print_function
from __future__ import unicode_literals
import base64
from Crypto import Random
from Crypto.Cipher import AES
class Cipher(object):
def __init__(self, key):
self.key = Cipher._pad(key[:32]).encode()
def decrypt(self, enc_msg):
enc_msg = base64.b64decode(enc_msg)
iv = enc_msg[:AES.block_size]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
decrypted = Cipher._unpad(cipher.decrypt(enc_msg[AES.block_size:]))
return decrypted.decode('utf-8')
def encrypt(self, msg):
msg = Cipher._pad(msg).encode()
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
joined = b''.join([iv, cipher.encrypt(msg)])
return base64.b64encode(joined)
@staticmethod
def _pad(s_):
bs = 32
if len(s_) == bs:
return s_
return ''.join(
[s_, (bs - len(s_) % bs) * chr(bs - len(s_) % bs)])
@staticmethod
def _unpad(s_):
return s_[:-ord(s_[len(s_)-1:])]
if __name__ == "__main__":
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment