Exploring Crypto-JS in Google Apps Script: Decoding the Mystery of C.lib

Recently, I decided to incorporate Crypto-JS into my Google Apps Script project. After transferring all of the source files to my workspace, I encountered a problem.

Specifically, when attempting to encrypt data using its AES feature, I stumbled upon an issue with the line below in the aes.js file:

var C_lib = C.lib;

As someone new to JavaScript, this prompted me to question: How do I properly reference and utilize C.lib within Google Apps Script? Furthermore, what exactly is C.lib? My attempts to find helpful resources on both Google and Stack Overflow have been unsuccessful thus far.

Answer №1

In the file core.js:

/**
 * Library namespace.
 */
var C_lib = C.lib = {};

It appears that every file in the CryptoJS package uses something similar to this:

var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var BlockCipher = C_lib.BlockCipher;

Therefore, it is likely necessary to include a reference to core.js if you are using the development version.

An example from CryptoJS 3.1:

<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<script>
    var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");

    var decrypted = CryptoJS.AES.decrypt(encrypted, "Secret Passphrase");
</script>

This example works without needing any additional links.

Answer №2

  • One of the main challenges when importing external libraries in apps script is the lack of support for modules.

  • Another issue you may encounter is with unsupported classes and methods.

For example, when dealing with cryptoJS,

  • You will need to manually determine dependencies, which are typically listed in the initial lines of a script using require or define. These lines can be found in the provided links within the script.

  • In terms of unsupported classes, apps script does not provide native support for the crypto library found in both node and window environments. Unfortunately, this limitation cannot be bypassed as far as I know. Consequently, you may only use older versions of CryptoJS rather than the latest ones.

Sample script:

function getCryptoJS() {
  const baseUrl = (file, version = '3.3.0') =>
    `https://unpkg.com/crypto-js@${version}/${file}.js`;

  const require = ((store) => (file) => {
    if (Array.isArray(file)) return file.forEach(require);
    if (store[file]) return;
    store[file] = true;
    eval(UrlFetchApp.fetch(baseUrl(file.slice(2))).getContentText());
  })({});

  /**
   * AES
   * @see https://github.com/brix/crypto-js/blob/31d00127a7c87066c51abe56e7b8be3a32141cae/aes.js#L8 for dependencies
   */
  const dependenciesAES = [
    './core',
    './enc-base64',
    './md5',
    './evpkdf',
    './cipher-core',
    './aes',
  ];
  require(dependenciesAES);
  const ciphertext = CryptoJS.AES.encrypt(
    'my message',
    'secret key 123'
  ).toString();

  /**
   * SHA3
   * @see https://github.com/brix/crypto-js/blob/31d00127a7c87066c51abe56e7b8be3a32141cae/sha3.js#L4 for  dependencies list
   */
  const dependenciesSHA3 = ['./core', './x64-core', './sha3'];
  dependenciesSHA3.forEach(require);
  const hash = CryptoJS.SHA3('Message');
  console.log({ ciphertext, hash: hash.toString() });
}

You can utilize all the supported methods in CryptoJS 3.3.0(=3.1.9-1) in a similar manner.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The art of bringing a pseudo class to life through animation

Seeking assistance with achieving a unique effect on click event. I have set up a slanted or razor-blade style div using a parent div element and a pseudo-element :after (as shown below). My goal is to change the skew angle when the user clicks on the pare ...

Conceal the <p> tag if the content inside is either "0" or blank

I'm currently working on a basic calculator project and I've hit a roadblock. I need to hide certain elements based on conditions. The code snippet with explanations is provided below. function calculateArea() { var length = document.getElem ...

Creating a customizable triangle design using the power of three.js

Recently, I came across the three.js library and I'm eager to incorporate it into my projects. One idea I have is to create a 2D triangle shape with hand holds on the vertices which allow me to adjust the shape in real-time. Can anyone provide guidanc ...

Encountering incorrect JSON formatting even though the content is accurate

I'm encountering an error while trying to fetch the JSON. It seems to be in the wrong format. Below is the JSON data: { "favorite_page_response": "<div class=\"col-md-12 col-lg-12\">\n <div class=\"cart\ ...

How to eliminate the "br" tags automatically inserted after each paragraph in TinyMCE version 6

I have been trying to work with TinyMCE version 6 and I am struggling to prevent the addition of <br> after each paragraph. Whenever I insert a line of text and press enter, a new paragraph is created but there is always a <br> added between t ...

Change the CSS of a table row when a link is in focus

Is there a way to style a <tr> element when an <a> tag inside of it is focused? Below is the HTML for the table: <table> <tr> <td> <a href"#" tabindex="1" accesskey="e">edit</a> &l ...

Executing mailto URLs from action method

As a newcomer to MVC, I am looking to create an action method in MVC that triggers Mailto:?body=body goes here.&subject=test subject, allowing the default mail client to automatically populate the user's email. Currently, I have a List<String&g ...

Exploring various queries in Firestore

Does anyone know if there is a way to create a sentence similar to this one: return this.db.collection('places', ref => ref.where("CodPais", "<>", pais)).valueChanges(); I have tried using != and <> but neither seem to be valid. ...

Display a new view upon clicking a button using AngularJS in a single-page web application

I am completely new to AngularJS and currently working on my first project. I apologize in advance if my question seems very basic. In my project, I have created a page using simple HTML with three buttons. When these buttons are clicked, I want to load v ...

Encountering issues with HMR after relocating files to the /app directory

Greetings, I am currently in the process of learning how to utilize express with webpacks HMR feature. However, every time I make changes and save a file, I encounter the following error: "The following modules couldn't be hot updated: (Full reload n ...

JkMegaMenu drop-down menus in Chrome are shifting to the left when the window is resized

Currently, I am utilizing the JKmegamenu plugin to incorporate a megamenu into a website that is currently under development. The megamenu functions properly and has an attractive appearance. However, there seems to be an issue where the drop-down divs shi ...

Instructions on integrating a column of buttons into a Bootstrap table containing information retrieved from a MySQL database

My bootstrap table is currently displaying data that is loaded from a MySQL database. I am looking to enhance it by adding a column with buttons, similar to the layout shown in this image. https://i.stack.imgur.com/8fWfR.png However, I am facing some dif ...

Parsing data from a CSV file and organizing the values into a structure in the C programming language

Currently, I am working on a project that involves reading data from a CSV file and storing each field in a variable within a struct. To extract the fields, I am using fgets and strtok functions. However, I have encountered a challenge with fields that con ...

Positioning the close button on the top right edge of a Material-UI Dialog: A step-by-step guide

https://i.sstatic.net/ARTtq.png How can I include a close icon in the top right corner of the header section? I'm using the Material UI Dialog and everything works well, but I need a close button in the top section. Can anyone assist me with this? ...

Do enum values get resolved during preprocessing or during compilation?

At what point are enum values resolved? Put simply, does the code snippet below comply with standards? enum{ A, B, MAX } #if MAX > 42 # error "Whoa! MAX surpasses 42!" #endif ...

Ways to eliminate the identical element from an array

In my JavaScript code, I'm working with an array like this: ['html', 'css', 'perl', 'c', 'java', 'javascript'] I want to know how to remove the "perl" element from this array. The objectiv ...

Revamping the dimensions of an array

I find it interesting that according to the definition of an array, we are not able to change its size. However, if I add an element to an existing array by shifting other elements to the right, the size of the array will increase. How is this possible? ...

Incorporate href along with ng-click for improved functionality

I need a link that will call a $scope-function when clicked, which will then display another view. I also want the user to be able to right-click on the link and open it in a new window or bookmark it. Unfortunately, the current html code is not worki ...

Encountering parameter issues while working with Google Maps React in TypeScript

Currently, I'm utilizing TypeScript in this particular file. import React, {Component} from 'react' import {Map, InfoWindow, Marker, GoogleApiWrapper, mapEventHandler, markerEventHandler} from 'google-maps-react'; import { coordina ...

Unable to access parameters from Pug template when using onclick event

I am facing an issue with my pug template test.pug. It contains a button that, when clicked, should call a function using parameters passed to the template from the rendering endpoint. Below is the structure of my template: doctype html html head tit ...