加密

../_images/33907152824_bf91078cc1_k_d.jpg

加密

cryptography 是一个主动开发的库,提供加密配方和原语。它支持python 2.6-2.7、python 3.3+和pypy。

密码学分为两层配方和危险品(危险品)。配方层为适当的对称加密提供了一个简单的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 bindings 提供进入 GPG Made Easy 是整个GNU隐私保护项目套件的C API,包括gpg、libgcrypt和gpgsm(s/mime引擎)。它支持python 2.6、2.7、3.4及更高版本。依赖于Python的swigC接口以及gnupg软件和库。

更全面的 GPGME Python Bindings HOWTO 源文件可用,HTML版本可用 at http://files.au.adversary.org .howto示例中的python 3示例脚本也随源代码一起提供,并且可以访问 at gnupg.org .

与gnupg项目的其余部分(gplv2和lgplv2.1)的条款相同,都有“或任何更高版本”条款。

安装

默认情况下,在编译gpgme时,如果配置脚本找到受支持的python版本(如果在配置期间它位于$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