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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this one helped me :)
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.