【发布时间】:2019-05-22 16:00:06
【问题描述】:
在此函数中,我尝试从文件中读取 Fernet 密钥,或者如果文件不包含密钥,则创建一个。
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)
我在阅读文件时遇到了困难。当文件被读取时,密钥被读取为:
b'nNjpIl9Ax2LRtm-p6ryCRZ8lRsL0DtuY0f9JeAe2wG0='
但我收到此错误:
ValueError: Fernet key must be 32 url-safe base64-encoded bytes.
在这一行:
Ecy = Fernet(Key)
任何帮助将不胜感激。
【问题讨论】:
-
执行
f = Fernet(b'nNjpIl9Ax2LRtm-p6ryCRZ8lRsL0DtuY0f9JeAe2wG0=')对我来说很好。 -
如果您直接将字节字符串放入命令而不是从文本文件中读取它,我相信它确实可以正常工作。必须与 csv 阅读器有关。
-
那么,您复制的字节字符串与
print(Key)的输出不完全一致吗? -
不,但如果您查看错误,则密钥的格式一定不正确。
标签: python python-3.x csv cryptography