Decode a Base64 String using CryptoJS

后端 未结 1 499
小蘑菇
小蘑菇 2020-12-13 15:53

I am trying to create a simple webpage with the goal to send and encrypted message to the server (which will create a file with that content), then a link is created and the

相关标签:
1条回答
  • 2020-12-13 16:39

    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.

    0 讨论(0)
提交回复
热议问题