디지털포렌식(Digital forensic)/키(key)
[파일] pycryptodome를 이용한 암호화, 복호화
이정욱교수
2023. 12. 1. 16:10
반응형
파이썬에서 가장 많이 사용되는 두 개의 암호화 라이브러리는
“cryptography”와 “pycryptodome”이다.
이 중 pycryptodome을 이용해 암호화 평문을 만들고 복호화를 만드는 코드를 파이썬으로 만들어본다.
먼저, 라이브러리를 설치한다.
설치 후 다음과 같은 파일을 만들고 실행한다.
import sys
# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
# 키 생성
key = get_random_bytes(16)
# AES 암호화 객체 생성
cipher = AES.new(key, AES.MODE_CBC)
# 평문 데이터
plaintext = "Hello, It's a secret message "
# 평문 데이터를 바이트로 변환하고 패딩 적용
plaintext_bytes = plaintext.encode('utf-8')
padded_data = pad(plaintext_bytes, AES.block_size)
# 암호화
ciphertext = cipher.encrypt(padded_data)
# 암호문 출력
print("암호문:", ciphertext.decode(sys.stdout.encoding, errors='replace'))
# 복호화를 위한 AES 객체 생성
decipher = AES.new(key, AES.MODE_CBC, iv=cipher.iv)
# 복호화
decrypted_data = unpad(decipher.decrypt(ciphertext), AES.block_size)
# 복호화된 데이터 출력
print("복호화된 데이터:", decrypted_data.decode('utf-8'))
위 파일을 실행하면 아래와 같이 평문 Hello, It's a secret message이 암호화 되고,
암호화된 텍스트가 다시 복호화되어 표시된다.
728x90