我正在尝试将使用python密码模块(https://cryptography.io/en/latest/)生成的Fernet密钥写入.txt文件。然后读取此.txt文件以检索密钥。
from cryptography.fernet import Fernet
import csv
#Creates textfile if textfile has not been created
with open("Keys.txt", "w+") as csvfile:
csvfile.close()
with open("Keys.txt","rU") as csvfile:
reader=csv.reader(csvfile)
KeyFound=0
for row in reader:
if len(row)>0:
KeyFound=1
Key=row
print(Key)
else:
pass
if KeyFound==0:
Key = Fernet.generate_key()
print(Key)
print("Created Key")
csvfile.close()
#Writing Key to textfile
if KeyFound==0:
with open("Keys.txt", "w+") as csvfile:
writer=csv.writer(csvfile)
writer.writerow(Key)
csvfile.close()
但是,当我运行此代码时,它会产生一个bytes
字符串而不是密钥。
示例:
铁网密钥:b'jDyzNLo3aPD6-zFGVRnzMyBdyy93wQhemJ8QR4VH2I0='
编写为:
106,68,121,122,78,76,111,51,97,80,68,54,45,122,70,71,86,82,110,122,77,121,66,100,121,121,57,51,119,81,104,101,109,74,56,81,82,52,86,72,50,73,48,61
我希望.txt文件包含密钥:b'jDyzNLo3aPD6-zFGVRnzMyBdyy93wQhemJ8QR4VH2I0='
我对此事进行了研究,我知道b'
表示字节字符串,但是我仍然不知道为什么将其表示为字节数列表而不是b'jDyzNLo3aPD6-zFGVRnzMyBdyy93wQhemJ8QR4VH2I0='
我知道将密钥保存到.txt文件可能不是最安全的方法,因此欢迎使用其他任何方法。
答案 0 :(得分:0)
发生这种情况是因为这是预期的行为。来自Python csv official docs
作家对象
Writer对象(DictWriter实例和 writer()函数)具有以下公共方法。 行必须是 Writer对象的字符串或数字的可迭代性和字典 将字段名称映射为字符串或数字(通过将它们传递给 首先将str()用于DictWriter对象。
尝试使用DictWriter(和DictReader)
with open("Keys.txt", "w+") as csvfile:
headers = ['key']
writer=csv.DictWriter(csvfile, fieldnames=headers)
writer.writeheader()
writer.writerow({'key': b'jDyzNLo3aPD6-zFGVRnzMyBdyy93wQhemJ8QR4VH2I0='})
csvfile.close()