How can I base64-encode unicode strings in JavaScr

2020-07-18 10:21发布

问题:

I need an encript arithmetic, which encript text to text.

the input text could be unicode, and the output should be a-z A-Z 0-9 - . (64 char max)

and it could be decrypt to unicode again.

it should implement in javascript and python.

If there is already some library could do this, great, if there is not, could you tell me.

Let me talk about why

To cheat China Greate Fire Wall , and GAE https has been blocked at china. Angry for this damn goverment.

回答1:

You might want to look at the base64 module. In Python 2.x (starting with 2.4):

>>> import base64
>>> s=u"Rückwärts"
>>> s
u'R\xfcckw\xe4rts'
>>> b=base64.b64encode(s.encode("utf-8"))
>>> b
'UsO8Y2t3w6RydHM='
>>> d=base64.b64decode(b)
>>> d
'R\xc3\xbcckw\xc3\xa4rts'
>>> d.decode("utf-8")
u'R\xfcckw\xe4rts'
>>> print d.decode("utf-8")
Rückwärts


回答2:

You are looking for a base64 encoding. In JavaScript and Python 2 this is a bit complicated as the latter doesn't support unicode natively and for the former you would need to implement an Unicode encoding yourself.

Python 3 solution

>>> from base64 import b64encode, b64decode
>>> b64encode( 'Some random text with unicode symbols: äöü今日は'.encode() )
b'U29tZSByYW5kb20gdGV4dCB3aXRoIHVuaWNvZGUgc3ltYm9sczogw6TDtsO85LuK5pel44Gv'
>>> b64decode( b'U29tZSByYW5kb20gdGV4dCB3aXRoIHVuaWNvZGUgc3ltYm9sczogw6TDtsO85LuK5pel44Gv' )
b'Some random text with unicode symbols: \xc3\xa4\xc3\xb6\xc3\xbc\xe4\xbb\x8a\xe6\x97\xa5\xe3\x81\xaf'
>>> _.decode()
'Some random text with unicode symbols: äöü今日は'