跳转到内容

Python加密库使用指南

cryptography 是一个功能强大且易于使用的 Python 加密库,旨在为开发人员提供安全且高效的加密原语和配方。

使用 pip 模块安装工具进行安装:

Terminal window
pip install cryptography

使用 cryptography.fernet 模块可以方便地进行对称加密。

  • 生成密钥 (Key)
from cryptography.fernet import Fernet
# 生成一个安全的随机密钥
key = Fernet.generate_key()
  • 数据加密
from cryptography.fernet import Fernet
fernet = Fernet(key)
# 对二进制明文数据进行加密
cry_res = fernet.encrypt(b'plain text')
  • 数据解密
from cryptography.fernet import Fernet
fernet = Fernet(key)
# 对加密后的密文进行解密还原
raw_res = fernet.decrypt(cry_res)