简体   繁体   English

加密模块是 Fernet 安全的,我可以使用该模块进行 AES 加密吗?

[英]Cryptography module is Fernet safe and can i do AES encryption with that module?

我可以使用密码学模块进行 AES 加密,什么是 Fernet,它是否像 AES 加密一样安全?

As Scott Arciszewski answered in a comment, Fernet is basically AES128 in CBC mode with a SHA256 HMAC message authentication code.正如Scott Arciszewski在评论中回答的那样, Fernet基本上是 CBC 模式下的 AES128,带有 SHA256 HMAC 消息身份验证代码。

A full specification of the Fernet construction can be found here .可以在此处找到 Fernet 结构的完整规范。

Fernet made more sense before GCM came around, as correctly implementing CBC + HMAC by yourself is difficult, and the CBC mode requires padding to 16 byte blocks. Fernet 在 GCM 出现之前更有意义,因为自己正确实现 CBC + HMAC 很困难,而且 CBC 模式需要填充到 16 字节块。

It is still safe but I would not recommend it for new systems because AES256-GCM combines encryption and authentication into the same standard protocol, which can be en/decrypted by browsers (Javascript subtle crypto API) and all other crypto libraries and tools, not just the Python cryptography module.它仍然是安全的,但我不建议将它用于新系统,因为 AES256-GCM 将加密和身份验证结合到相同的标准协议中,可以由浏览器(Javascript 微妙的加密 API)和所有其他加密库和工具对其进行加密/解密,而不是只是 Python 加密模块。 The GCM mode is also a lot faster, reaching several gigabytes per second with AES-NI. GCM 模式也快得多,使用 AES-NI 达到每秒几 GB。

It is unfortunate that it is hidden deep inside the hazmat module:不幸的是,它隐藏在hazmat模块的深处:

import secrets
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

# Generate a random secret key (AES256 needs 32 bytes)
key = secrets.token_bytes(32)

# Encrypt a message
nonce = secrets.token_bytes(12)  # GCM mode needs 12 fresh bytes every time
ciphertext = nonce + AESGCM(key).encrypt(nonce, b"Message", b"")

# Decrypt (raises InvalidTag if using wrong key or corrupted ciphertext)
msg = AESGCM(key).decrypt(ciphertext[:12], ciphertext[12:], b"")

Even with the same key and the same message, the ciphertext will always be completely different (because of a different nonce).即使使用相同的密钥和相同的消息,密文也总是完全不同的(因为不同的随机数)。 Do note that ciphertext is always exactly 28 bytes longer than the message, so if the message length needs to be hidden, you could pad all messages to same length before encryption.请注意,密文总是比消息长 28 个字节,因此如果需要隐藏消息长度,您可以在加密之前将所有消息填充到相同的长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM