I want to run the following NodeJS code in Google app script
const CryptoJS = require("crypto-js");
let timeStamp_nonce = Date.now().toString();
let bodystring = `{"ID":"001"}`
const body = JSON.parse(bodystring)
const secret = "secret"
const msg= {
timeStamp_nonce: timeStamp_nonce,
body: JSON.stringify(body)
};
const payload = new Buffer(JSON.stringify(msg)).toString('base64');
const signature = CryptoJS.enc.Hex.stringify(CryptoJS.HmacSHA512(payload, secret));
console.log("Payload:", payload)
console.log("\nSignature:",signature)
I tried to convert:
let timeStamp_nonce = Date.now().toString();
let bodystring = `{"ID":"001"}`
const body = JSON.parse(bodystring)
const secret = "secret"
const msg = {
timeStamp_nonce: timeStamp_nonce,
body: JSON.stringify(body)
};
const payload = Utilities.base64Encode(JSON.stringify(msg));
//
// confused on this part...
//
//const signature = CryptoJS.enc.Hex.stringify(CryptoJS.HmacSHA512(payload, secret));
//
//
Logger.log("Payload:", i)
Logger.log("\nSignature:",signature)
Can anyone help with this to run in Google Apps script
I believe your goal as follows.
I think that this conversion can be achieved using the built-in functions of Google Apps Script. Please check the following sample script.
let timeStamp_nonce = Date.now().toString();
let bodystring = `{"ID":"001"}`
const body = JSON.parse(bodystring)
const secret = "secret"
const msg= {
timeStamp_nonce: timeStamp_nonce,
body: JSON.stringify(body)
};
const payload = Utilities.base64Encode(JSON.stringify(msg));
const bytes = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, payload, secret);
const signature = bytes.map(b => ('0' + (b & 0xFF).toString(16)).slice(-2)).join('');
console.log("Payload:", payload)
console.log("\nSignature:",signature)
When timeStamp_nonce
is "1234567890123"
, your script of Node.js returns the following values.
Payload: eyJ0aW1lU3RhbXBfbm9uY2UiOiIxMjM0NTY3ODkwMTIzIiwiYm9keSI6IntcIklEXCI6XCIwMDFcIn0ifQ==
Signature: bd291d4c05e1a217afd90e2036fad2f3273ed4e4eada909fe5878cf2e902849ec5b01b160e20d8f43b0564be83e4a74391ccd280d43771a12a1363e5458ad61d
I could confirm that about this result, when timeStamp_nonce = "1234567890123"
is used for above above Google Apps Script, the same result could be obtained.
Utilities.computeHmacSignature
is the bytes array of the signed hexadecimal. In this case, in order to achieve the conversion, it is required to convert the bytes array to the unsigned hexadecimal.