암호화(Cryptography)¶
cryptography¶
cryptography 는 활발히 개발되고 있는 라이브러리로, 암호화 레시피와 기본 구성요소를 제공합니다. 파이썬 2.6-2.7, 파이썬 3.3+, 그리고 PyPy를 지원합니다.
cryptography는 레시피 계층과 위험 요소(hazmat) 계층의 두 가지로 나누어져 있습니다. 레시피 계층은 적절한 대칭키 암호화를 위한 단순한 API를 제공하고, hazmat 계층은 저수준의 암호화 기본 구성요소를 제공합니다.
설치¶
$ pip install cryptography
예시¶
고수준 대칭키 암호화 레시피를 사용하는 예시 코드입니다:
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
cipher_text = cipher_suite.encrypt(b"A really secret message. Not for prying eyes.")
plain_text = cipher_suite.decrypt(cipher_text)
GPGME 바인딩¶
GPGME Python 바인딩 은 GPG, libgcrypt, gpgsm(S/MIME 엔진)을 포함한 GNU Privacy Guard 프로젝트 모음 전체를 위한 C API인 GPG Made Easy 에 파이썬다운 방식으로 접근할 수 있게 해줍니다. 파이썬 2.6, 2.7, 3.4 이상을 지원합니다. 파이썬용 SWIG C 인터페이스와 GnuPG 소프트웨어 및 라이브러리에 의존합니다.
더 포괄적인 GPGME Python Bindings HOWTO 가 소스와 함께 제공되며, HTML 버전은 files.au.adversary.org에서 볼 수 있습니다. HOWTO의 예시에서 가져온 파이썬 3 샘플 스크립트도 소스와 함께 제공되며 gnupg.org에서 접근할 수 있습니다.
GnuPG 프로젝트의 나머지와 동일한 조건, 즉 “or any later version” 조항이 포함된 GPLv2 및 LGPLv2.1 하에서 이용할 수 있습니다.
설치¶
GPGME를 컴파일할 때 configure 스크립트가 지원되는 파이썬 버전을 찾으면 기본으로 포함됩니다(설정 시 $PATH에 있으면 찾을 수 있습니다).
예시¶
import gpg
# Encryption to public key specified in rkey.
a_key = input("Enter the fingerprint or key ID to encrypt to: ")
filename = input("Enter the filename to encrypt: ")
with open(filename, "rb") as afile:
text = afile.read()
c = gpg.core.Context(armor=True)
rkey = list(c.keylist(pattern=a_key, secret=False))
ciphertext, result, sign_result = c.encrypt(text, recipients=rkey,
always_trust=True,
add_encrypt_to=True)
with open("{0}.asc".format(filename), "wb") as bfile:
bfile.write(ciphertext)
# Decryption with corresponding secret key
# invokes gpg-agent and pinentry.
with open("{0}.asc".format(filename), "rb") as cfile:
plaintext, result, verify_result = gpg.Context().decrypt(cfile)
with open("new-{0}".format(filename), "wb") as dfile:
dfile.write(plaintext)
# Matching the data.
# Also running a diff on filename and the new filename should match.
if text == plaintext:
print("Hang on ... did you say *all* of GnuPG? Yep.")
else:
pass
