首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Fernet解密时出错

使用Fernet解密时出错
EN

Stack Overflow用户
提问于 2022-06-07 17:41:08
回答 2查看 331关注 0票数 1

在使用fernet库创建了一个简单的python加密代码(非常有用)之后,我尝试编写一个解密器,但不幸的是,在尝试使用我的解密器时,我得到了以下错误

代码语言:javascript
复制
['blahblahblah.txt', 'blah.txt']
Traceback (most recent call last):
  File "/home/kali/Desktop/stuff/projects/voldemort/decrypt.py", line 24, in <module>
    contents_decrypted = Fernet(secretkey).decrypt(contents)
  File "/usr/lib/python3/dist-packages/cryptography/fernet.py", line 34, in __init__
    raise ValueError(
ValueError: Fernet key must be 32 url-safe base64-encoded bytes.

“守则”:

代码语言:javascript
复制
#!/usr/bin/python3

import os
from cryptography.fernet import Fernet

#find some files
files = []

#Starting the file in a loop
for file in os.listdir():
        if file == "voldemort.py" or file == "thekey.key" or file == "decrypt.py":
                continue
        if os.path.isfile(file):
                files.append(file)

print(files)

with open("thekey.key", "rb") as key:
        secretkey = key.read()

for file in files:
        with open(file, "rb") as thefile:
                contents = thefile.read()
        contents_decrypted = Fernet(secretkey).decrypt(contents)
        with open(file, "wb") as thefile:
                thefile.write(contents_decrypted)
EN

回答 2

Stack Overflow用户

发布于 2022-06-07 18:11:20

错误只说明使用的键无效。Fernet期待一个32字节的base64编码字符串作为密钥.

有许多方法可以生成这样的字符串,下面有两个简单的示例:

备选案文1:

Fernet为您做这件事:

代码语言:javascript
复制
from cryptography import fernet

key = fernet.Fernet.generate_key()

输出:

代码语言:javascript
复制
b'd25vYTghWVgkTQWrMFnwW1tfKtn_lWzDr2JJM95f2fs='

备选案文2:

使用(唯一的)随机生成的UUID4字符串自己创建一个:

代码语言:javascript
复制
import base64
import uuid

key = base64.b64encode(uuid.uuid4().hex.encode())

输出:

代码语言:javascript
复制
b'M2E4MmQ2MDJlNmZmNDQwN2I3Y2NiN2I0ZDJkMzA4Zjk=' 

针对有关为文件编写密钥的有益评论,可以使用:

代码语言:javascript
复制
with open('keyfile.key', 'wb') as f:
    f.write(key)

请记住,Fernet正在寻找字节串,所以使用'wb' (写二进制)模式存储文件很重要。

票数 1
EN

Stack Overflow用户

发布于 2022-06-07 17:50:01

您的问题是您的Fernet密钥没有正确编码。

*更新以支持原始文件输出

代码语言:javascript
复制
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
import hashlib
import zlib, base64, json

SALT = 'secretpassword'        

def cryptkey(password=''):
    digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
    digest.update(SALT+password)
    return Fernet(base64.urlsafe_b64encode(digest.finalize()))

def encrypt(meta, password=''):
    meta = str(zlib.compress(meta, 9))
    f = cryptkey(password)
    return base64.urlsafe_b64encode(f.encrypt(bytes(meta)))

def decrypt(meta, password=''):
    meta = base64.urlsafe_b64decode(meta)
    f = cryptkey(password)
    meta = f.decrypt(bytes(meta))
    return zlib.decompress(meta)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72535462

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档