Decode a Base64 String using CryptoJS

最后都变了- 提交于 2019-11-30 00:49:15

I ran into a similar confusion, and for reference, here is the solution.

To turn a text string (UTF-8 encoded) into a base-64 string, you need:

var textString = 'Hello world'; // Utf8-encoded string
var words = CryptoJS.enc.Utf8.parse(textString); // WordArray object
var base64 = CryptoJS.enc.Base64.stringify(words); // string: 'SGVsbG8gd29ybGQ='

To turn a base-64 encoded string back into text (UTF-8 encoded), it's:

var base64 = 'SGVsbG8gd29ybGQ=';
var words = CryptoJS.enc.Base64.parse(base64);
var textString = CryptoJS.enc.Utf8.stringify(words); // 'Hello world'

Some explanation

As you can see from the examples given in the CryptoJS documentation, parse is meant to parse a string in the format that the encoder is expecting (into a WordArray), and stringify turns a WordArray into a string.

From the documentation:

var words  = CryptoJS.enc.Base64.parse('SGVsbG8sIFdvcmxkIQ==');
var base64 = CryptoJS.enc.Base64.stringify(words); // 'Hello, World!'

The WordArray is CryptoJS's format-independent representation of data. Formatters (like Base64 and Utf8) are interfaces between this WordArray format, and strings, which may contain data encoded in any format. So to change between formats, you need a formatter at either end, one parsing and one stringifying (i.e. encoding). In this case, you need to remember that when we write 'Hello World', that's text encoded in a particular format (I'm assuming UTF-8).

I found this Gist helpful.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!