密码学

https://farm5.staticflickr.com/4220/33907152824_bf91078cc1_k_d.jpg

Cryptography

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

Cryptography 分为两个层,方法(recipes)层和危险底层(hazardous materials,简称hazmat)。方法层提供用于适当的对称加密,hazmat层提供底层的加密基元。

安装

  1. $ pip install cryptography

例子

示例代码使用了高层的对称加密方法:

  1. from cryptography.fernet import Fernet
  2. key = Fernet.generate_key()
  3. cipher_suite = Fernet(key)
  4. cipher_text = cipher_suite.encrypt(b"A really secret message. Not for prying eyes.")
  5. plain_text = cipher_suite.decrypt(cipher_text)

GPGME bindings

GPGME Python bindings 提供Pythonic的方式访问 GPG Made Easy ,这是整个GNU Privacy Guard项目套件,包括GPG、libgcrypt和gpgsm(S/MIME 引擎),的C API。它支持Python 2.6、2.7、3.4及以上版本。取决于Python的SWIG C接口以及GnuPG软件和库。

这里有更全面的GPGME Python Bindings HOWTO的 源码版HTML版。还提供了Python 3版本的HOWTO示例脚本的源代码,并且可以在 这里 访问。

其在与GnuPG其余项目的相同条款(GPLv2和LGPLv2.1,均带有“或更高版本”)下可用。

安装

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

例子

  1. import gpg
  2.  
  3. # Encryption to public key specified in rkey.
  4. a_key = input("Enter the fingerprint or key ID to encrypt to: ")
  5. filename = input("Enter the filename to encrypt: ")
  6. with open(filename, "rb") as afile:
  7. text = afile.read()
  8. c = gpg.core.Context(armor=True)
  9. rkey = list(c.keylist(pattern=a_key, secret=False))
  10. ciphertext, result, sign_result = c.encrypt(text, recipients=rkey,
  11. always_trust=True,
  12. add_encrypt_to=True)
  13. with open("{0}.asc".format(filename), "wb") as bfile:
  14. bfile.write(ciphertext)
  15. # Decryption with corresponding secret key
  16. # invokes gpg-agent and pinentry.
  17. with open("{0}.asc".format(filename), "rb") as cfile:
  18. plaintext, result, verify_result = gpg.Context().decrypt(cfile)
  19. with open("new-{0}".format(filename), "wb") as dfile:
  20. dfile.write(plaintext)
  21. # Matching the data.
  22. # Also running a diff on filename and the new filename should match.
  23. if text == plaintext:
  24. print("Hang on ... did you say *all* of GnuPG? Yep.")
  25. else:
  26. pass

PyCrypto

PyCrypto 是另一个密码库,它提供安全的哈希函数和各种加密算法,支持Python 2.1到3.3。

安装

  1. $ pip install pycrypto

例子

  1. from Crypto.Cipher import AES
  2. # Encryption
  3. encryption_suite = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
  4. cipher_text = encryption_suite.encrypt("A really secret message. Not for prying eyes.")
  5.  
  6. # Decryption
  7. decryption_suite = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
  8. plain_text = decryption_suite.decrypt(cipher_text)

原文: http://pythonguidecn.readthedocs.io/zh/latest/scenarios/crypto.html