在使用fernet库创建了一个简单的python加密代码(非常有用)之后,我尝试编写一个解密器,但不幸的是,在尝试使用我的解密器时,我得到了以下错误
['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.“守则”:
#!/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)发布于 2022-06-07 18:11:20
错误只说明使用的键无效。Fernet期待一个32字节的base64编码字符串作为密钥.
有许多方法可以生成这样的字符串,下面有两个简单的示例:
备选案文1:
让Fernet为您做这件事:
from cryptography import fernet
key = fernet.Fernet.generate_key()输出:
b'd25vYTghWVgkTQWrMFnwW1tfKtn_lWzDr2JJM95f2fs='备选案文2:
使用(唯一的)随机生成的UUID4字符串自己创建一个:
import base64
import uuid
key = base64.b64encode(uuid.uuid4().hex.encode())输出:
b'M2E4MmQ2MDJlNmZmNDQwN2I3Y2NiN2I0ZDJkMzA4Zjk=' 针对有关为文件编写密钥的有益评论,可以使用:
with open('keyfile.key', 'wb') as f:
f.write(key)请记住,Fernet正在寻找字节串,所以使用'wb' (写二进制)模式存储文件很重要。
发布于 2022-06-07 17:50:01
您的问题是您的Fernet密钥没有正确编码。
*更新以支持原始文件输出
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)https://stackoverflow.com/questions/72535462
复制相似问题