Search code examples
stringbase64jscript

How to decode a Base64 string in JScript


I have to decode a Base64 String in JScript, and I've tried this code for performing the purposed action :

var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
var el = xmlDom.createElement("tmp");
el.dataType = "bin.Base64"
el.text = "aGVsbG8gd29ybGQ=";
WScript.Echo(el.nodeTypedValue);

But, unfortunately, It doesn't work. It should show the message Hello world but the return message is a bunch of Chinese characters. Here's a screen as proof

enter image description here

And, Is there another method for decoding a Base64 encoded string?


Solution

  • You have to carry out some additional steps to get the textual representation of the decoded base-64.

    The result of el.nodeTypedValue will be an array of bytes containing the decoded base-64 data. This needs to be converted into a textual string. I have assumed utf-8 for the example but you may need to modify it to suit your text encoding.

    var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
    var el = xmlDom.createElement("tmp");
    el.dataType = "bin.Base64"
    el.text = "aGVsbG8gd29ybGQ=";
    //WScript.Echo(el.nodeTypedValue);
    
    // Use a binary stream to write the bytes into
    var strm = WScript.CreateObject("ADODB.Stream");
    strm.Type = 1;
    strm.Open();
    strm.Write(el.nodeTypedValue);
    
    // Revert to the start of the stream and convert output to utf-8
    strm.Position = 0;
    strm.Type = 2;
    strm.CharSet = "utf-8";
    
    // Output the textual equivalent of the decoded byte array
    WScript.Echo(strm.ReadText());
    strm.Close();
    

    Here is the output:

    Output image

    Note that this code is not production-worthy. You'll need to tidy up objects after their use is complete.

    There are other ways of converting an array of bytes to characters. This is just one example of it.