Python

Python AES 암/복호화

DevelopC 2017. 7. 2. 16:29
728x90

Python AES 암/복호화

아래의 코드를 사용하기 위해서 먼저 pycrypto 를 설치하셔야 합니다
$ pip install pycrypto
import base64
import hashlib
from Crypto.Cipher import AES


BS = 16
pad = (lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS).encode())
unpad = (lambda s: s[:-ord(s[len(s)-1:])])


class AESCipher(object):
    def __init__(self, key):
        self.key = hashlib.sha256(key.encode()).digest()

    def encrypt(self, message):
        message = message.encode()
        raw = pad(message)
        cipher = AES.new(self.key, AES.MODE_CBC, self.__iv())
        enc = cipher.encrypt(raw)
        return base64.b64encode(enc).decode('utf-8')

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        cipher = AES.new(self.key, AES.MODE_CBC, self.__iv())
        dec = cipher.decrypt(enc)
        return unpad(dec).decode('utf-8')

    def __iv(self):
        return chr(0) * 16


key = 'secretkey'
message = '테스트'
  
aes = AESCipher(key)
encrypt = aes.encrypt(message)
decrypt = aes.decrypt(encrypt)
  
print(encrypt)
print(decrypt)

 

 

728x90

'Python' 카테고리의 다른 글

Python animated gif 체크 방법  (0) 2019.08.13
Python json pretty print  (0) 2017.07.03
Python 네이버 블로그 글쓰기  (0) 2017.07.02