[英]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.