Hashing and Encoding in Javascript

Prev Next

When using hashing in the Catchpoint JavaScript API, it’s important to understand how it behaves compared to Selenium macros. The key difference is in the output format and how Hex conversion is handled.

Default Behavior

Both Selenium ${hash(...)} and Catchpoint.hash(...) return a digest in Base64 by default.

Example:

var md5hash = Catchpoint.hash("md5", "test123"); 
// md5hash = "zAPnR6avu8v4vnZorP6+5Q=="

Selenium vs. JavaScript API

In Selenium, you can directly convert a hash to Hex, for example:

${hex(${hash(md5, "test123")})}

In the JavaScript API, this is different. Helpers like Catchpoint.encode(..., "hex") and Catchpoint.hex(...) work on strings, not on the raw hash digest. This is why simply calling them won’t give the same result as Selenium.

Operation Selenium Example JavaScript API Example Result
MD5 of “test123” ${hash(md5,"test123")} Catchpoint.hash("md5", "test123") zAPnR6avu8v4vnZorP6+5Q== (Base64)
Hex of MD5 (direct) {hex({hash(...)})} Catchpoint.encode(..., "hex") Incorrect → not the digest
Correct Hex of digest {hex({hash(...)})} Decode Base64 → Encode Hex cc03e747a6afbbcbf8be7668acfebee5

Correct Way to Get Hex in JavaScript API

To replicate Selenium’s ${hex(${hash(...)})}, you must first decode the Base64 string (digest) into raw bytes, then convert those bytes into Hex:

function encodeHex(asciiStr) {
    var hex = "";
    for (var i = 0; i < asciiStr.length; i++) {
        var h = asciiStr.charCodeAt(i).toString(16);
        hex += (h.length === 1 ? "0" : "") + h;
    }
    return hex;
}

function decodeBase64(s) {
    var map = {}, i, b = 0, c, x, l = 0, a, r = '', w = String.fromCharCode;
    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for (i = 0; i < 64; i++) { map[chars.charAt(i)] = i; }

    for (x = 0; x < s.length; x++) {
        c = map[s.charAt(x)];
        b = (b << 6) + c;
        l += 6;
        while (l >= 8) {
            (a = (b >>> (l -= 8)) & 0xff) && (r += w(a));
        }
    }
    return r;
}

var b64 = Catchpoint.hash("md5", "test123");   // Base64 digest
var hex = encodeHex(decodeBase64(b64));        // Proper Hex result
// hex = "cc03e747a6afbbcbf8be7668acfebee5"

Helper Function Behavior (Clarification)

  • Catchpoint.hash(...) → Always returns Base64
  • Catchpoint.encode(..., "hex") → Works on a string, not the digest
  • Catchpoint.hex(...) → Same, Hex of string
  • Catchpoint.encode(..., "base64") → Encodes a string to Base64
  • Catchpoint.decode(..., "base64") → Decodes Base64 into UTF-8

Important Note: None of these helpers directly reproduce Selenium’s ${hex(${hash(...)})}. Manual conversion (decode Base64 → encode Hex) is required.

Key Takeaways

• If you just need a digest: Catchpoint.hash(...) gives Base64 directly.
• If you specifically need Hex: you must decode the Base64 digest into raw bytes and then re-encode it yourself.