모듈 설치
$ pip install pycryptodome
예제 코드
import base64
from Crypto import Random
from Crypto.Cipher import AES
class AES256():
def __init__(self, key):
self.bs = 128
self.key = key.encode('utf-8')
self.key = AES256.str_to_bytes(key)
@staticmethod
def str_to_bytes(data):
u_type = type(b''.decode('utf8'))
if isinstance(data, u_type):
return data.encode('utf8')
return data
def _pad(self, s):
return s + (self.bs - len(s) % self.bs) * AES256.str_to_bytes(chr(self.bs - len(s)%self.bs))
@staticmethod
def _unpad(s):
return s[:-ord(s[len(s)-1:])]
def encrypt(self, raw):
raw = self._pad(AES256.str_to_bytes(raw))
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw)).decode('utf-8')
def decrypt(self, enc):
enc = base64.b64decode(enc)
iv = enc[:AES.block_size]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')
aes256 = AES256('mypassword')
e_aes256 = aes.encrypt('password_encrypt')
print(e_aes256) # VvDWrD2aDyc+2rsdfDhDKosnc2odl2HD2
print(aes256.decrypt(e_aes256)) # password_encrypt
'Programming > Python' 카테고리의 다른 글
| Python - Product vs Permutations vs Combinations (0) | 2024.08.18 |
|---|---|
| Python - Numpy란 [1] (0) | 2023.11.18 |
| Python - 클로저와 __call__ 함수 (0) | 2023.06.18 |
| Python - 파이썬 코딩의 기술을 통한 클린코딩 (0) | 2023.06.11 |
| Python - ModuleNotFoundError : No module named (0) | 2023.03.27 |