cryptography.fernet使用哪个加密密码?

Which encryption password does cryptography.fernet uses?

我正在制作一个加密和解密文本的程序。我正在使用 Python 3.7 和 cryptography.fernet 库。我想在 GitHub 页面输入一些关于我程序的加密标准的信息,但我不明白 Fernet 使用哪种加密方式。

这是我在项目中使用的示例代码。我想用 256 位 (AES-256) 密钥加密,但此代码生成的密钥超过 32 个字符。这是44个字符。但在密码学库的官方网站上,它说这段代码生成 128 位密钥。这个 44 个字符(352 位)密钥的名称是什么?或者有什么方法可以不用 PyCrypto 实现 256 位对称加密吗?

from cryptography.fernet import Fernet
import base64
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

textEncrypt = "Secret Data"
password = "Password"
salt = os.urandom(16)
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),length=32,salt=salt,iterations=100000)
key = base64.urlsafe_b64encode(kdf.derive(password))
fernet = Fernet(key)
encryptedText = fernet.encrypt(textEncrypt.encode())

这是这段代码生成的密钥:aAT_LESBw_ZGlPA52cj4zQd6jBdx6gk5RmQWbpLY7e0=

文档里写的很好;

Implementation

Fernet is built on top of a number of standard cryptographic primitives. Specifically it uses:

  • AES in CBC mode with a 128-bit key for encryption; using PKCS7 padding.
  • HMAC using SHA256 for authentication.
  • Initialization vectors are generated using os.urandom().

For complete details consult the specification.

因此您不能将 AES-256 与 Fernet 一起使用

PyCrypto 可以使用 AES-256 的广泛操作模式,包括 CBC、CTR、GCM、SIV 和 OCB


不清楚你是怎么得到44字节的,这里是得到32字节的方法;

from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import base64
import os


textEncrypt = "Secret Data"
password = "Password"
salt = os.urandom(16)
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),length=32,salt=salt,iterations=100000)

key = kdf.derive(str.encode(password))
print(len(key))
print(key)

并输出

32
b'K\xf6\x10a\xd6B`\x8a\x83\x13\xc2\xcfOJ\xcb\x02k$~\xf7v\x01\x80\xd0\xda\x93!\xaf\xa9B\x94\xfe'