python和node base64解码之间的区别 [英] difference between python and node base64 decoding

查看:215
本文介绍了python和node base64解码之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这个base64解码问题感到困惑,似乎python和node.js的处理方式有所不同.我相信Node可以正确做到这一点.任何人都可以帮助指出python为什么在这里不起作用吗?

I am puzzled at this base64 decoding issue, and it seems that python and node.js does this differently. Node does this correctly I believe. Could anyone help point out why python does not work here?

谢谢.

节点

> console.log(Buffer.from('Im3Osc6_z4HPgc-J==', 'base64').toString());
"mαορρω

Python

>>> from base64 import decodestring
>>> print decodestring('Im3Osc6_z4HPgc-J==')
"mαγ?s?p

推荐答案

您提供的实际上不是标准的base64,而是URL安全的base64

What you provided is actually not a standard base64, but a URL-safe base64

在标准Base64字母表中用-代替+_代替/"

要在Python中对其进行解码,您需要使用 base64.urlsafe_b64decode .

To decode it in Python you need to use base64.urlsafe_b64decode.

>>> import base64
>>> base64.urlsafe_b64decode('Im3Osc6_z4HPgc-J==')
'"m\xce\xb1\xce\xbf\xcf\x81\xcf\x81\xcf\x89'

然后,在那个base64中编码的字节字符串在UTF-8中;要获取Unicode字符串,您必须对其进行解码:

Then, the byte string that is encoded in that base64 is in UTF-8; to get a Unicode string, you have to decode it:

>>> print base64.urlsafe_b64decode('Im3Osc6_z4HPgc-J==').decode('utf-8')
"mαορρω

使用base64.decodestring时,您会得到奇怪的结果,因为它会丢弃不属于标准base64字母的任何字符,因此会解码不正确的字节.

With base64.decodestring you got weird results because it just drops any character that is not part of the standard base64 alphabet, so it decoded incorrect bytes.

这篇关于python和node base64解码之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆