gpt4 book ai didi

python - 将 Fernet key 写入文本文件会生成字节字符串而不是 ASCII 字符串

转载 作者:太空宇宙 更新时间:2023-11-03 21:25:26 24 4
gpt4 key购买 nike

我正在尝试将使用 python 加密模块( https://cryptography.io/en/latest/ )生成的 Fernet key 写入 .txt 文件。然后读取该 .txt 文件以检索 key 。

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 字符串而不是 key 。

示例:Fernet key :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 文件包含 key :b'jDyzNLo3aPD6-zFGVRnzMyBdyy93wQhemJ8QR4VH2I0='

我对这个问题做了一些研究,我知道 b' 表示一个字节字符串,但我仍然不知道为什么它被表示为字节数字列表而不是 b'jDyzNLo3aPD6-zFGVRnzMyBdyy93wQhemJ8QR4VH2I0='

我知道将 key 保存到 .txt 文件可能不是最安全的方法,因此欢迎任何其他方法。

最佳答案

发生这种情况是因为这是预期的行为。来自Python csv official docs

Writer Objects

Writer objects (DictWriter instances and objects returned by the writer() function) have the following public methods. A row must be an iterable of strings or numbers for Writer objects and a dictionary mapping fieldnames to strings or numbers (by passing them through str() first) for DictWriter objects.

尝试使用 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()

关于python - 将 Fernet key 写入文本文件会生成字节字符串而不是 ASCII 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53870130/

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