[英]Writing a Fernet Key to a textfile yields a bytes string instead of ASCII String
我正在尝试将使用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='
密钥: 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文件可能不是执行此操作的最安全方法,因此欢迎使用任何其他方法。
发生这种情况是因为这是预期的行为。 来自Python CSV 官方文档
作家对象
Writer对象(DictWriter实例和writer()函数返回的对象)具有以下公共方法。 对于Writer对象 , 行必须是字符串或数字的可迭代项;对于DictWriter对象,字典必须将字段名映射为字符串或数字(首先将它们通过str()传递)的字典。
尝试使用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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.