python 密码学库_6.16. 密码学 |《Python 最佳实践指南 2018 2018》| Python 技术论坛

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)

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接

我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值