从 Python 中的部分行读取 base64
Reading base64 from a part line in Python
我目前正在为一些我认为应该是基本的事情而苦苦挣扎,目前我有一个程序要求用户输入并将其保存为 base64 编码的字符串,
password = base64.b64encode(values['password'].encode('utf-8'))
在 PySimpleGui 中输入密码的地方 window。这非常有效,因此
'password' = "password"
password = b'cGFzc3dvcmQ='
解码工作正常
password = (base64.b64decode(rig.password)).decode('utf-8')
然而,当我将这个值保存到一个文件中,然后尝试将其加载回内存时,问题就来了。
filedir = 'Rigdata.txt'
rigfile = open(filedir, 'w',encoding="utf-8")
for rig in rigs:
rigdata = ["\n\nRig "+str(rig.number)+"\n\tRig Number ;"+str(rig.number)+"\n\tRig ID ;"+str(rig.name)+"\n\tIP Address ;"+str(rig.ip)+"\n\tFTP Username ;"+str(rig.username)+"\n\tFTP Password ;"+str(rig.password)]
rigfile.writelines(rigdata)
rigfile.close()
它以
格式存储在文件中
some words; the value being saved
然后将其逐行读回 class 中,将字符串分成 2 部分,只保留分号后的所有内容。
password = str(rigdata.readline().replace("\n","")).split(';')[1]
然而,当读取它时 returns base64 作为字符串,无论我是否进行拆分并将其称为字符串...这都会导致解码失败,因为它的长度错误。
"b'cGFzc3dvcmQ='"
有什么方法可以轻松纠正这个问题以便我可以解码密码吗?
非常感谢!
您需要几个编码步骤才能将该字符串值转换为原始密码。
参考: https://stackabuse.com/encoding-and-decoding-base64-strings-in-python/#decodingstringswithpython
>>> import base64
>>> a = "b'cGFzc3dvcmQ='"
>>> a.split("'")
['b', 'cGFzc3dvcmQ=', '']
>>> b = a.split("'")[1]
>>> b
'cGFzc3dvcmQ='
>>> b64_bytes = b.encode("ascii")
>>> b64_bytes
b'cGFzc3dvcmQ='
>>> string_bytes = base64.b64decode(b64_bytes)
>>> string_bytes
b'password'
>>> string = string_bytes.decode("ascii")
>>> string
'password'
我目前正在为一些我认为应该是基本的事情而苦苦挣扎,目前我有一个程序要求用户输入并将其保存为 base64 编码的字符串,
password = base64.b64encode(values['password'].encode('utf-8'))
在 PySimpleGui 中输入密码的地方 window。这非常有效,因此
'password' = "password"
password = b'cGFzc3dvcmQ='
解码工作正常
password = (base64.b64decode(rig.password)).decode('utf-8')
然而,当我将这个值保存到一个文件中,然后尝试将其加载回内存时,问题就来了。
filedir = 'Rigdata.txt'
rigfile = open(filedir, 'w',encoding="utf-8")
for rig in rigs:
rigdata = ["\n\nRig "+str(rig.number)+"\n\tRig Number ;"+str(rig.number)+"\n\tRig ID ;"+str(rig.name)+"\n\tIP Address ;"+str(rig.ip)+"\n\tFTP Username ;"+str(rig.username)+"\n\tFTP Password ;"+str(rig.password)]
rigfile.writelines(rigdata)
rigfile.close()
它以
格式存储在文件中some words; the value being saved
然后将其逐行读回 class 中,将字符串分成 2 部分,只保留分号后的所有内容。
password = str(rigdata.readline().replace("\n","")).split(';')[1]
然而,当读取它时 returns base64 作为字符串,无论我是否进行拆分并将其称为字符串...这都会导致解码失败,因为它的长度错误。
"b'cGFzc3dvcmQ='"
有什么方法可以轻松纠正这个问题以便我可以解码密码吗?
非常感谢!
您需要几个编码步骤才能将该字符串值转换为原始密码。
参考: https://stackabuse.com/encoding-and-decoding-base64-strings-in-python/#decodingstringswithpython
>>> import base64
>>> a = "b'cGFzc3dvcmQ='"
>>> a.split("'")
['b', 'cGFzc3dvcmQ=', '']
>>> b = a.split("'")[1]
>>> b
'cGFzc3dvcmQ='
>>> b64_bytes = b.encode("ascii")
>>> b64_bytes
b'cGFzc3dvcmQ='
>>> string_bytes = base64.b64decode(b64_bytes)
>>> string_bytes
b'password'
>>> string = string_bytes.decode("ascii")
>>> string
'password'