Encrypting and Decrypting with AES using crypto-js with Google Apps Script

Gists

This is a sample script for encrypting and decrypting with AES using crypto-js with Google Apps Script.

Unfortunately, in the current stage, Google Apps Script cannot encrypt and decrypt AES using the built-in functions. In this post, in order to achieve this, “crypto-js” is used from cdnjs.com ( https://cdnjs.com/libraries/crypto-js ). In the current stage, it seems that the main functions of crypto-js.min.js can be directly used with Google Apps Script. But, unfortunately, all functions cannot be used. Please be careful about this.

In this sample, I would like to introduce a sample script for encrypting and decrypting with AES using crypto-js with Google Apps Script.

Sample script

In this sample, when you run myFunction in the script editor of Google Apps Script, the result can be seen.

function myFunction() {
  const cdnjs =
    "https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js";
  eval(UrlFetchApp.fetch(cdnjs).getContentText());

  const k1 = "0123456789012345"; // Sample key
  const k2 = "5432109876543210"; // Sample key
  const str = "sample text"; // Sample text

  const key = CryptoJS.enc.Utf8.parse(k1);
  const iv = CryptoJS.enc.Utf8.parse(k2);

  // Encrypting
  const res1 = CryptoJS.AES.encrypt(str, key, { iv }).toString();
  console.log(res1); // <--- wyMY7zKADagvk1Z98gjIbw==

  // Decrypting
  var res2 = CryptoJS.enc.Utf8.stringify(
    CryptoJS.AES.decrypt(res1, key, { iv })
  );
  console.log(res2); // <--- sample text
}

IMPORTANT

In this sample, the script of https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js is loaded with eval. If you cannot use this, you can also use this script by copying and pasting the script of https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js to the script editor. By this, you can remove eval(UrlFetchApp.fetch(cdnjs).getContentText());. When the script of crypto-js.min.js is put in the script editor, the process cost can be reduced rather than that using eval(UrlFetchApp.fetch(cdnjs).getContentText());.

References

 Share!