I would like to us Crypto-JS
in Google Apps Script and have copied all source files into my project.
When trying to encrypt data with its AES
The main problem with importing external libraries in apps script is the sheer lack of any support for modules.
The other problem would be unsupported classes/methods.
In case of cryptoJS,
Dependencies need to be manually figured out. It is usually recorded in the first few lines of a script using require
or define
. The following links in script shows such lines.
About unsupported classes, apps script doesn't support native crypto
library that is present both in node
and window
. In this case, the problem cannot be circumvented AFAIK. Therefore It is not possible to use latest versions of CryptoJS. But older versions can be used.
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() });
}
In a similar way, you can use all the supported methods in CryptoJS 3.3.0(=3.1.9-1)