使用Python2与Python3进行Base64 URL解码
我正在尝试对十六进制字符串进行base64 url解码。但是,我无法使用Python3正确解码字符串 十六进制字符串是使用Python2与Python3进行Base64 URL解码,python,python-3.x,python-2.7,decode,Python,Python 3.x,Python 2.7,Decode,我正在尝试对十六进制字符串进行base64 url解码。但是,我无法使用Python3正确解码字符串 十六进制字符串是614756736247395862334a735a41,ASCII等价物是“aGVsbG9Xb3JsZA”。解码的字符串应该是helloWorld 我的代码是 str_encoded = "614756736247395862334a735a41" byte_encoded = binascii.unhexlify(str_encoded) print(ba
614756736247395862334a735a41
,ASCII等价物是“aGVsbG9Xb3JsZA”。解码的字符串应该是helloWorld
我的代码是
str_encoded = "614756736247395862334a735a41"
byte_encoded = binascii.unhexlify(str_encoded)
print(base64.urlsafe_b64decode(str(byte_encoded) + '=' * (4 - len(str(byte_encoded)))))
print(base64.urlsafe_b64decode("aGVsbG9Xb3JsZA=="))
如果我用Python2运行上面的代码,我会得到正确的解码字符串helloWorld
。但是如果我使用Python3运行,第一个print
给出了错误的结果
为什么会有区别?除了在Python3中使用
binascii.unhexlify()
,我应该使用什么替代方法?区别在于python2中的unhexlify()
返回一个str
对象和Python3的-bytes
,因为python2没有这样的类。
在Python3中对bytes对象运行str()
函数时,该对象只会得到一个repr()
,因此Python3中的str(byte_编码)
返回b“…”
,如果希望它在两个版本中都运行,我建议您打开str(byte_编码)
转换为仅字节编码
并解码字节编码
变量,如果它是Python3,则如下所示:
str_encoded = "614756736247395862334a735a41"
byte_encoded = binascii.unhexlify(str_encoded)
try:
byte_encoded = byte_encoded.decode()
except:
pass
print(base64.urlsafe_b64decode(byte_encoded + '=' * (4 - len(str(byte_encoded)))))
print(base64.urlsafe_b64decode("aGVsbG9Xb3JsZA=="))
你期望len(str(byte_encoded))产生什么结果?你得到的错误结果是什么?您的意思是您得到了一个异常
binascii.Error:填充不正确
?@mkrieger1不,没有错误,但解码的字符串不是helloWorld