gpt4 book ai didi

python - 读取 Fernet Key 导致 ValueError : Fernet key must be 32 url-safe base64-encoded bytes

转载 作者:行者123 更新时间:2023-11-28 22:13:30 27 4
gpt4 key购买 nike

在这个函数中,我试图从文件中读取 Fernet key ,如果文件不包含 key ,则创建一个。

from cryptography.fernet import Fernet
import csv


with open("Keys.txt","rU") as csvfile:
reader=csv.reader(csvfile)
KeyFound=0
print(KeyFound)
for row in reader:
try:
print(row[0])
except IndexError:
continue
if len(row[0])>4:
print("KEY FOUND")
KeyFound=1
print(KeyFound)
Key=row[0]
print(Key)
print(KeyFound)
else:
pass
if KeyFound==0:
Key = Fernet.generate_key()
print(Key)
print("Created Key")
csvfile.close()
#Writing Key to textfile
with open("Keys.txt", "w+") as csvfile:
headers = ['key']
writer=csv.DictWriter(csvfile, fieldnames=headers)
writer.writeheader()
writer.writerow({'key': Key})
csvfile.close()
print(Key)
Ecy = Fernet(Key)

我在阅读文件时遇到困难。读取文件时, key 读入为:

b'nNjpIl9Ax2LRtm-p6ryCRZ8lRsL0DtuY0f9JeAe2wG0='

但是我收到这个错误:

ValueError: Fernet key must be 32 url-safe base64-encoded bytes.

在这一行中:

Ecy = Fernet(Key)

如有任何帮助,我们将不胜感激。

最佳答案

这里的问题是如何将 key 写入文件。

Fernet.generate_key() 返回一个 bytes 实例:

>>> key = Fernet.generate_key()
>>> key
b'ZmDfcTF7_60GrrY167zsiPd67pEvs0aGOv2oasOM1Pg='

key 按原样写入文件:

>>> with open('keys.csv', 'w+') as f:
... headers = ['key']
... writer = csv.DictWriter(f, fieldnames=headers)
... writer.writeheader()
... writer.writerow({'key': key})
...
49
>>>

如果我们查看文件,我们可以看到内容不是我们所期望的 - b 表示 python 字节串已写入文件:

$  cat keys.csv 
key
b'ZmDfcTF7_60GrrY167zsiPd67pEvs0aGOv2oasOM1Pg='

csv.writer对任何还不是字符串的值调用 str。如果在 bytes 实例上调用 str,您将获得字节实例的字符串化 repr 而不是 bytes< 的解码值 实例,这就是你想要的*

>>> str(key)
"b'ZmDfcTF7_60GrrY167zsiPd67pEvs0aGOv2oasOM1Pg='" # <- note the extra quotes...
>>> key.decode('utf-8')
'ZmDfcTF7_60GrrY167zsiPd67pEvs0aGOv2oasOM1Pg='

所以解决方法是在csv.writer之前调用bytes实例的decode方法收到它。

>>> with open('keys.csv', 'w+') as f:
... headers = ['key']
... writer = csv.DictWriter(f, fieldnames=headers)
... writer.writeheader()
... writer.writerow({'key': key.decode('utf-8')})
...
46
>>>

这给了我们想要的文件内容:

$  cat keys.csv 
key
ZmDfcTF7_60GrrY167zsiPd67pEvs0aGOv2oasOM1Pg=

其余代码按预期工作:

>>> with open('keys.csv') as f:
... reader = csv.reader(f)
... next(reader) # <- skip the header row
... for row in reader:
... csv_key = row[0]
... print(Fernet(csv_key))
...
['key'] # <- the headers are printed as a side effect of skipping
<cryptography.fernet.Fernet object at 0x7f3ad62fd4e0>

一个调试技巧。使用 print() 调试代码时,有时打印对象的 repr 会更好。 ,而不是在对象上调用 str 的结果(这是 print() 所做的)。如果对象是字符串,情况尤其如此。例如:

>>> bad_key = str(key)
>>> print(bad_key)
b'ZmDfcTF7_60GrrY167zsiPd67pEvs0aGOv2oasOM1Pg=' # <- Looks ok...
>>> print(repr(bad_key))
"b'ZmDfcTF7_60GrrY167zsiPd67pEvs0aGOv2oasOM1Pg='" # <- See the problem
>>>
>>> good_str = 'foo'
>>> bad_str = 'foo '
>>> print(bad_str)
foo # <- looks like good_str
>>> print(repr(bad_str))
'foo ' # <- see the trailing space

* 如果您使用 -b 标志调用 Python - python -b myscript.py - Python 将发出一个 BytesWarning 他第一次尝试在 bytes 实例上调用 str。如果使用 -bb 标志,将引发异常。

关于python - 读取 Fernet Key 导致 ValueError : Fernet key must be 32 url-safe base64-encoded bytes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53897333/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com