Notice
Recent Posts
Recent Comments
Link
SeouliteLab
파이썬으로 GPG 암호화 및 복호화하기: pygpgme 라이브러리 활용하기 본문
GPG(GNU Privacy Guard)는 데이터의 암호화 및 전자 서명을 지원하는 오픈 소스 암호화 소프트웨어입니다. 파이썬에서 GPG를 사용하여 데이터를 암호화하거나 복호화할 수 있는 라이브러리인 pygpgme를 사용하면 편리합니다. 이번에는 pygpgme를 사용하여 파이썬에서 GPG를 활용하는 방법을 알아보겠습니다.
예제 1: 텍스트 암호화 및 복호화
import gpg
# GPG 객체 생성
gpgme = gpg.Context()
# 암호화할 텍스트
plain_text = "암호화할 내용입니다."
# 암호화
cipher_text, _ = gpgme.encrypt(plain_text, recipients=["recipient@example.com"])
# 복호화
decrypted_text, _ = gpgme.decrypt(cipher_text)
print("암호화된 텍스트:", cipher_text)
print("복호화된 텍스트:", decrypted_text)
위 예제는 pygpgme를 사용하여 텍스트를 암호화하고 복호화하는 방법을 보여줍니다. encrypt()
메서드를 사용하여 텍스트를 암호화하고, decrypt()
메서드를 사용하여 암호문을 복호화합니다.
예제 2: 파일 암호화 및 복호화
import gpg
# GPG 객체 생성
gpgme = gpg.Context()
# 암호화할 파일
file_to_encrypt = "file_to_encrypt.txt"
# 파일 암호화
with open(file_to_encrypt, "rb") as f:
cipher_text, _ = gpgme.encrypt(f.read(), recipients=["recipient@example.com"])
# 복호화된 파일 저장
with open("decrypted_file.txt", "wb") as f:
decrypted_text, _ = gpgme.decrypt(cipher_text)
f.write(decrypted_text)
이 예제는 파일을 암호화하고 복호화하는 방법을 보여줍니다. encrypt()
메서드를 사용하여 파일을 암호화하고, decrypt()
메서드를 사용하여 암호문을 복호화한 후 새로운 파일에 저장합니다.
예제 3: 서명 생성 및 검증
import gpg
# GPG 객체 생성
gpgme = gpg.Context()
# 서명할 텍스트
plain_text = "서명할 내용입니다."
# 서명 생성
signature, _ = gpgme.sign(plain_text)
# 서명 검증
verified, _ = gpgme.verify(signature)
print("서명 검증 결과:", verified)
위 예제는 pygpgme를 사용하여 서명을 생성하고 검증하는 방법을 보여줍니다. sign()
메서드를 사용하여 텍스트에 서명을 생성하고, verify()
메서드를 사용하여 서명을 검증합니다.
pygpgme를 사용하면 파이썬에서 GPG를 통해 데이터를 안전하게 암호화하고 복호화할 수 있습니다.