1

我试过这个:

from cryptography import *
try:
    #code here to create key from a password
    f=Fernet(key)
    token=f.decrypt(data)
except cryptography.fernet.InvalidToken:
    print("wow")

但它仍然会引发错误。

4

1 回答 1

1

来自文档

解密(令牌,ttl=无)

提高:

  • cryptography.fernet.InvalidToken – 如果令牌以任何方式无效,则会引发此异常。令牌可能因
    多种原因无效:它比 ttl 旧、格式错误或
    没有有效签名。
  • TypeError – 如果令牌不是字节,则会引发此异常。

你应该使用:

from cryptography import *
import cryptography

try:
    #code here to create key from a password
    f=Fernet(key)
    token=f.decrypt(data)
except (cryptography.fernet.InvalidToken, TypeError):
    print("wow")

此外,key应该是字节——一个 URL 安全的 base64 编码的 32 字节密钥。


如果您有以下错误消息:

Error: Incorrect padding

这是生成的,因为在类中,它正在对您Fernet的构造函数应用base64.decodestringkey

key = base64.urlsafe_b64decode(key)

要捕获您可以使用的错误:

from binascii import Error
from cryptography import *
import cryptography

try:
    #code here to create key from a password
    f=Fernet(key)
    token=f.decrypt(data)
except (cryptography.fernet.InvalidToken, TypeError, Error):
    print("wow")
于 2020-03-29T10:50:14.553 回答