SBM ModScript, Part 13 - Base64Encode

Someone recently asked me if it is possible to base64 encode a string in ModScript... so I did.

def Base64Encode( string input ) {
  add_global_const("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", "CONST_BASE64TABLE");
  
  var sOut = "";
  
  var buf = [uint8_t(),uint8_t(), uint8_t()];
  var idx = -1;

  for ( c : input ) {
    buf[++idx] = c;
    if (idx == 2) {
      // Output the 4 encoded bytes
      sOut += CONST_BASE64TABLE[buf[0] >> 2];                              // first 6-bits of byte 0
      sOut += CONST_BASE64TABLE[(((buf[0] & 0x03) << 4)) | (buf[1] >> 4)]; // last 2-bits of byte 0 + first 4-bits of byte 1
      sOut += CONST_BASE64TABLE[(((buf[1] & 0x0f) << 2)) | (buf[2] >> 6)]; // last 4-bits of byte 1 + first 2-bits of byte 2
      sOut += CONST_BASE64TABLE[buf[2] & 0x3f];                            // last 6-bits of byte 2

      idx = -1;
    }
  }

  // Special case handling of last 1 or 2 characters
  if ( idx != -1 ) {
    sOut += CONST_BASE64TABLE[buf[0] >> 2];             // first 6-bits of byte 0
    
    if (idx == 0) {
      sOut += CONST_BASE64TABLE[((buf[0] & 0x03) << 4)];  // last 2-bits of byte 0
      sOut += '=';                                  // pad
    }
    else if (idx == 1) {
      sOut += CONST_BASE64TABLE[(((buf[0] & 0x03) << 4)) | (buf[1] >> 4)]; // last 2-bits of byte 0 + first 4-bits of byte 1
      sOut += CONST_BASE64TABLE[((buf[1] & 0x0f) << 2)];                   // last 4-bits of byte 1
    }
    
    sOut += '=';                                  // pad
  }
  
  sOut; // return
}

 

The function above iterates the string contents and uses base64 to create an encoded output string. Notice that the "buf" variable is a Vector of 3 unsigned, 8 bit integers. As we are going to use bit shifting in order to encode the data, it is important to use unsigned byte data to ensure the expected bit-shift result. We then use the bit-shifted value to index into CONST_BASE64TABLE to find the data-representation we are looking for. The result is a base64 encoding of the string data. 

A likely use-case for this would be when adding custom headers to a RESTDataSource call-out.

 

SBM ModScript - Table of Contents

NEW COURSE: 3166 – ZENWORKS 2017 MOBILE MANAGEMENT...
SBM MODSCRIPT, PART 14 - Checking the Type of a Va...

Comments

 
No comments yet

Recent Tweets