Python Package

cryptography

2025-11-27

cryptography 是 [[Python]] 加密工具包,提供了多种加密算法的实现,包括对称加密、非对称加密、哈希算法等。

安装

通过 [[pip]] 安装:

Terminal window
pip install cryptography

cryptography

Fernet

Fernet 保证使用它加密的消息无法在不使用密钥的情况下被篡改或读取。

.generate_key()

生成一个新的 fernet 密钥。

from cryptography.fernet import Fernet
Fernet.generate_key() # -> bytes
# 返回: b'xr5uCs8-AB3dX-ouhuagDNjCO95mUEm79OY5Oz_5acQ='

.encrypt()

加密传递的数据:。

f.encrypt(data: bytes) # -> bytes
  • data: 希望加密的数据,必须是 bytes;
from cryptography.fernet import Fernet
Fernet.generate_key() # -> bytes
f.encrypt(b"hello, world!") # -> bytes

.decrypt()

对加密的内容进行解密

f.decrypt(token, ttl=None) # -> bytes
  • token: 加密后的数据,也就是调用 .encrypt() 的结果

使用

通过 Ferent 进行加密和解密

from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
# 加密
token = f.encrypt(b"hello, world!")
# 解密
f.decrypt(token)

除了使用 .generate_key() 生成之外,也可以用指定的字符串,比如用 immwind.com 作为 key:

from cryptography.fernet import Fernet
import hashlib, base64
str_key = b"immwind.com"
str_data = b"hello, world!"
key = hashlib.sha256(str_key).digest()
base64_key = base64.urlsafe_b64encode(key)
f = Fernet(key)
# 加密
token = f.encrypt(str_data)
# 返回: b'gAAAAABpZPiyR78C-aE0BMIPw4nhPh1X_n5_pEQqPFBSECro_fln7Dpz2exK7R7KwK4qPXKrN_R3PWm6z97g8RuCdtGE-uI0YQ=='
# 解密
f.decrypt(token)
# 返回: b'hello, world!'

参考