Skip to content

Instantly share code, notes, and snippets.

@chongkong
Last active May 18, 2016 08:50
Show Gist options
  • Save chongkong/a28734e4503cf2d34a98740c2718643c to your computer and use it in GitHub Desktop.
Save chongkong/a28734e4503cf2d34a98740c2718643c to your computer and use it in GitHub Desktop.
AES Encrypt/Decrypter using PyCrypto
import random
import string
from base64 import b64decode, b64encode
from Crypto.Cipher import AES
BLOCK_SIZE = 128 // 8
def pkcs7_pad(s):
pad_len = BLOCK_SIZE - (len(s) % BLOCK_SIZE)
return s + (pad_len * chr(pad_len))
def pkcs7_unpad(s):
pad_len = ord(s[-1])
return s[:-pad_len]
class Aes128Cipher(object):
def __init__(self, clip_key):
self.key = clip_key[:32]
self.iv = clip_key[:16]
@property
def aes(self):
"""매번 새로운 AES 객체를 만들어야 한다"""
return AES.new(self.key, AES.MODE_CBC, self.iv)
def encrypt(self, s):
return b64encode(self.aes.encrypt(pkcs7_pad(s))).decode()
def decrypt(self, s):
return pkcs7_unpad(self.aes.decrypt(b64decode(s)).decode())
def test():
aes = Aes128Cipher('oe123ry7f8iqdsghfbhjaslfjfuyrbeg')
random_str = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(123))
assert aes.encrypt('110236') == 'xjB4l+Zb3v88x2OTV+FEmA=='
assert aes.decrypt(aes.encrypt(random_str)) == random_str
print('All Test Passed')
if __name__ == '__main__':
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment