Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python2与Python3进行Base64 URL解码_Python_Python 3.x_Python 2.7_Decode - Fatal编程技术网

使用Python2与Python3进行Base64 URL解码

使用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

我正在尝试对十六进制字符串进行base64 url解码。但是,我无法使用Python3正确解码字符串

十六进制字符串是
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