[英]Converting string to bytes
我有一个具有以下格式的文件:
username password (base64 encoded) id
我必须读取此密码(base64编码)并对其进行解码,以作为密码中的参数传递进行身份验证。 问题是,当我读取此密码时,它将被读取为字符串,并且在尝试解码时会收到错误消息,因为这预计是字节。
def getSecret(self):
home = expanduser("~/.user/credentials")
with open(home,"r") as file:
self.password = list(file)[1]
self.password = base64.b64decode(self.password)
return self.password
conn = User()
decode = base64.b64decode(conn.getSecret())
print(decode)
但这返回一个字符串,应该是字节,当我尝试解码时我得到了这个错误
return binascii.a2b_base64(s)
binascii.Error: Incorrect padding
我该如何读取和解码?
谢谢。
您有一个要解码的Python string
:
>>> password_b64='c2VjcmV0\n'
binascii.a2b_base64
函数将执行此操作( 注意: a2b
):
>>> binascii.a2b_base64(password_b64)
b'secret'
但是它返回一个bytes
对象,而不是一个string
对象。 因此,您必须以某种方式解码字节。 显而易见的方法是假定它们是UTF-8,然后对结果bytes
调用.decode(encoding)
方法:
>>> binascii.a2b_base64(password_b64).decode("utf-8")
'secret'
我发现了问题,只需要从字符串中删除b''就可以了。 非常感谢大家。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.