简体   繁体   English

将字符串转换为字节

[英]Converting string to bytes

I have a file that have this format: 我有一个具有以下格式的文件:

username password (base64 encoded) id

I have to read this password (base64 encoded) and decode it to pass as a paramater in the password to authenticate. 我必须读取此密码(base64编码)并对其进行解码,以作为密码中的参数传递进行身份验证。 The problem is, when I read this password it is being readed as string and I get an error when I try to decode because this is expecting to be bytes. 问题是,当我读取此密码时,它将被读取为字符串,并且在尝试解码时会收到错误消息,因为这预计是字节。

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)

But this is returning a string and should be bytes, when I try to decode this i got this error 但这返回一个字符串,应该是字节,当我尝试解码时我得到了这个错误

return binascii.a2b_base64(s)
binascii.Error: Incorrect padding

How can I read and decode this? 我该如何读取和解码?

Thank you. 谢谢。

You have a Python string that you want to decode: 您有一个要解码的Python string

>>> password_b64='c2VjcmV0\n'

The binascii.a2b_base64 function will do that ( NOTE: a2b ): binascii.a2b_base64函数将执行此操作( 注意: a2b ):

>>> binascii.a2b_base64(password_b64)
b'secret'

But it returns a bytes object, not a string object. 但是它返回一个bytes对象,而不是一个string对象。 So you have to decode the bytes somehow. 因此,您必须以某种方式解码字节。 The obvious way is to presume they are UTF-8, and invoke the .decode(encoding) method on the resulting bytes : 显而易见的方法是假定它们是UTF-8,然后对结果bytes调用.decode(encoding)方法:

>>> binascii.a2b_base64(password_b64).decode("utf-8")
'secret'

I found the problem, just had to remove the b'' from the string and everything worked. 我发现了问题,只需要从字符串中删除b''就可以了。 Thank you very much everyone. 非常感谢大家。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM