6.16. 密码学 | python 应用场景 |《python 最佳实践指南 2018 2018》| python 技术论坛-江南app体育官方入口

未匹配的标注

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 绑定

 提供 pythonic 风格的方式访问  的接口,这是一套 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

 是另一个加密函数库,提供安全散列函数和各种加密算法。适用于 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)

本文章首发在 江南app体育官方入口 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 cc 协议,如果我们的工作有侵犯到您的权益,请及时联系江南app体育官方入口。

原文地址:https://learnku.com/docs/python-guide/20...

译文地址:https://learnku.com/docs/python-guide/20...

上一篇 下一篇
讨论数量: 0



暂无话题~
网站地图