pip install pycryptodome
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
def encrypt(plain_text, key):
# 16 바이트(128비트)의 임의의 키 생성
initialization_vector = get_random_bytes(16)
# 암호화할 데이터를 패딩 처리
padded_plain_text = pad(plain_text.encode(), AES.block_size)
# AES 암호화 객체 생성 및 초기화
cipher = AES.new(key.encode(), AES.MODE_CBC, initialization_vector)
# 데이터를 암호화
encrypted_data = cipher.encrypt(padded_plain_text)
# 초기화 벡터와 암호문을 합쳐서 반환
return initialization_vector + encrypted_data
def decrypt(encrypted_data, key):
# 초기화 벡터와 암호문 분리
initialization_vector = encrypted_data[:16]
encrypted_data = encrypted_data[16:]
# AES 복호화 객체 생성 및 초기화
cipher = AES.new(key.encode(), AES.MODE_CBC, initialization_vector)
# 데이터를 복호화하고 언패딩 처리
decrypted_data = unpad(cipher.decrypt(encrypted_data), AES.block_size)
# 복호화된 데이터 반환
return decrypted_data.decode()
# 암호화할 문자열과 키 설정
plain_text = "Hello, World!"
key = "ThisIsASecretKey"
# 문자열 암호화
encrypted_text = encrypt(plain_text, key)
print("암호화된 문자열:", encrypted_text)
# 암호문 복호화
decrypted_text = decrypt(encrypted_text, key)
print("복호화된 문자열:", decrypted_text)
댓글