Python pycryptodome

Happy_JG·2024년 4월 3일

Python library

목록 보기
2/2

필요한 모듈 임포트

from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES
import base64

# AESCipher 클래스 정의
class AESCipher:
    def __init__(self, key):
        self.key = key

    def encrypt(self, raw):
        cipher = AES.new(self.key, AES.MODE_CBC)
        ciphertext_bytes = cipher.encrypt(raw.ljust(len(raw) + AES.block_size - len(raw) % AES.block_size))
        return base64.b64encode(ciphertext_bytes)

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        cipher = AES.new(self.key, AES.MODE_CBC)
        decrypted_bytes = cipher.decrypt(enc)
        return decrypted_bytes.rstrip(b"\0").decode("utf-8")

# AESCipher 객체 생성
key = get_random_bytes(16)  # 16바이트(128비트)의 임의의 키 생성
aes_cipher = AESCipher(key)

# 텍스트 암호화 및 복호화
plaintext = "Hello, World!"
encrypted_text = aes_cipher.encrypt(plaintext)
decrypted_text = aes_cipher.decrypt(encrypted_text)

# 결과 출력
print("원본 텍스트:", plaintext)
print("암호화된 텍스트:", encrypted_text)
print("복호화된 텍스트:", decrypted_text)
profile
hello!

0개의 댓글