首页 > Python > Python 最佳实践指南 2018 > Python 应用场景

6.16. 密码学

file

Cryptography

Cryptography 是一个开发活跃的库,它提供 了加密方法(recipes)和基元(primitives),支持 Python 2.6-2.7、Python 3.3+ 和 PyPy。

Cryptography 分为两个层,方法(recipes)层和危险底层(hazardous materials,简称 hazmat)。 方法层提供用于适当的对称加密,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 绑定 提供 Pythonic 风格的方式访问 GPG Made Easy 的接口,这是一套 C API 用以访问整个 GNU Privacy Guard 项目套件,包括 GPG、libgcrypt 和 gpgsm(S/MIME 引擎)项目。它支持 Python 2.6、2.7、3.4 及以上版本。取决于 Python 的 SWIG C 接口以及 GnuPG 软件和库。

本项目的开源协议与 GnuPG 的其他项目相同,都是 GPLv2 和 LGPLv2.1,并兼容后续版本。

安装

如果配置脚本定位到了所支持的 Python 版本(配置时位于 $PATH 中),那么在编译 GPGME 时会默认包含它。

示例

import gpg
import os

# 加密在 rkey 中指定的公钥。
rkey = "0xDEADBEEF"
text = "Something to hide."
plain = gpg.core.Data(text)
cipher = gpg.core.Data()
c = gpg.core.Context()
c.set_armor(1)
c.op_keylist_start(rkey, 0)
r = c.op_keylist_next()
c.op_encrypt([r], 1, plain, cipher)
cipher.seek(0, os.SEEK_SET)
ciphertext = cipher.read()

# 用相应的秘钥解密
# 调用 gpg-agent 和 pinentry.
plaintext = gpg.Context().decrypt(ciphertext)

# 匹配数据。
if text == plaintext[0].decode("utf-8"):
    print("Hang on ... did you say *all* of GnuPG?  Yep.")
else:
    pass

PyCrypto

PyCrypto 是另一个加密函数库,提供安全散列函数和各种加密算法。适用于 Python 2.1到3.3版本。

安装

$ pip install pycrypto

示例

from Crypto.Cipher import AES
# 加密
encryption_suite = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
cipher_text = encryption_suite.encrypt("A really secret message. Not for prying eyes.")

# 解密
decryption_suite = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
plain_text = decryption_suite.decrypt(cipher_text)