2

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?

Eugen-Andrei Coliban
  • 1,060
  • 2
  • 12
  • 40

2 Answers2

1

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.

Martin
  • 16,093
  • 1
  • 29
  • 48
1

If you run the JScript code from an HTA, you can use atob:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=11">
</head>
<body>
<script language="JScript">
  text = "Hello world!";
  encoded = window.btoa(text);
  alert(encoded);
  decoded = window.atob(encoded);
  alert(decoded);
  self.close();
</script>
</body>
</html>
LesFerch
  • 1,540
  • 2
  • 5
  • 21