Encoding and Decoding Base64 with the N/crypto Module

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 */
define(['N/crypto', 'N/log'], function (crypto, log) {

  function onRequest(context) {
    let text = 'Sample Data';
     
    // Encode to Base64
    let encoded = crypto.encode({
      input: text,
      outputEncoding: crypto.Encoding.BASE_64
    });

    log.debug('Encoded (Base64):', encoded);

    // Decode from Base64
    let decoded = crypto.decode({
      input: encoded,
      inputEncoding: crypto.Encoding.BASE_64
    });

    log.debug('Decoded:', decoded);

    context.response.write('Encoded: ' + encoded + '<br>Decoded: ' + decoded);
  }

  return {
    onRequest: onRequest
  };
});

How It Works

  • crypto.encode() converts a plain text string into a Base64-encoded string.
  • crypto.decode() reverses the process, converting it back to readable text.
  • This is useful for handling special characters in URLs, encoding API keys, or storing data in a compressed format.

Other Supported Encoding Formats

The N/crypto module supports multiple encoding formats:

  • crypto.Encoding.UTF_8
  • crypto.Encoding.BASE_64
  • crypto.Encoding.HEX

Leave a comment

Your email address will not be published. Required fields are marked *