[python] PyCrypto를 이용한 대칭키 암호화 방법
대칭키 암호화는 동일한 키를 사용하여 데이터를 암호화하고 복호화하는 방식입니다. Python에서 PyCrypto 라이브러리를 사용하면 대칭키 암호화를 간편하게 구현할 수 있습니다.
설치
먼저 PyCrypto 라이브러리를 설치해야 합니다. 아래의 명령어를 사용하여 설치할 수 있습니다.
pip install pycrypto
암호화 예제
다음은 PyCrypto를 사용하여 대칭키 암호화를 수행하는 간단한 예제입니다.
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
def encrypt(key, data):
cipher = AES.new(key, AES.MODE_EAX)
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(data.encode())
return nonce + ciphertext + tag
def decrypt(key, data):
nonce = data[:16]
ciphertext = data[16:-16]
tag = data[-16:]
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
plaintext = cipher.decrypt_and_verify(ciphertext, tag)
return plaintext.decode()
# 키 생성
key = get_random_bytes(16)
# 데이터 암호화
encrypted_data = encrypt(key, "암호화할 데이터")
# 데이터 복호화
decrypted_data = decrypt(key, encrypted_data)
위의 예제에서는 AES 대칭키 알고리즘을 사용하고 있습니다. encrypt
함수는 주어진 키와 데이터를 암호화하고, decrypt
함수는 암호화된 데이터를 복호화합니다. get_random_bytes
함수를 사용하여 임의의 키를 생성할 수 있습니다.