Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I base64-encode unicode strings in JavaScript and Python?

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.

like image 630
guilin 桂林 Avatar asked Dec 09 '22 13:12

guilin 桂林


2 Answers

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
like image 170
Tim Pietzcker Avatar answered Dec 12 '22 03:12

Tim Pietzcker


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: äöü今日は'
like image 22
poke Avatar answered Dec 12 '22 03:12

poke