티스토리 뷰

반응형

1. pycrypto 설치필요

pip install pycrypto

2. 암호화, 복호화 클래스

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().encode('utf8'))
        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().encode('utf8'))
        dec = cipher.decrypt(enc)
        return unpad(dec).decode('utf-8')
    
    def __iv(self):
        return chr(0) * 16

3. 사용예

key = "this is key"
data = "암호화 대상문장 입니다"

aes = AESCipher(key)

encrypt = aes.encrypt(data)
print("암호화:", encrypt)
print("-"*100)

decrypt = aes.decrypt(encrypt)
print("복호화:", decrypt)
print("-"*100)

4. 결과

반응형
반응형
최근에 달린 댓글