问题
Is there a way to create a hash value in Google Apps Script? Google Apps Script will run server side code in the .gs
code file. The .gs
file is written in JavaScript. Because JavaScript is mostly a client side language, and encrypting anything client side isn't secure, maybe something like HMAC for Javascript isn't available? When I do a web search on hmac in javascript
the first thing I get is crypto-js
. But it looks like I need to link to some services in <script>
tags:
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-md5.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha1.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha256.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha512.js"></script>
<script>
var hash = CryptoJS.HmacMD5("Message", "Secret Passphrase");
var hash = CryptoJS.HmacSHA1("Message", "Secret Passphrase");
var hash = CryptoJS.HmacSHA256("Message", "Secret Passphrase");
var hash = CryptoJS.HmacSHA512("Message", "Secret Passphrase");
</script>
The Secret Passphrase
would be in your client side HTML. That doesn't make any sense! Oh! I just found some pseudocode in wikipedia.
Wikipedia HMAC pseudo Code
Here is my attempt at refactoring it:
//blocksize is the size in bytes and is set to 64 bytes.
//byte size of any UTF-8 string
function byteCount(s) {
return encodeURI(s).split(/%..|./).length - 1;
};
function hmac(key, message) {
var blocksize = 64;
var keyLngth = byteCount(key);
if (keyLngth > blocksize) {
key = hash(key); // keys longer than blocksize are shortened
}
else if (keyLngth < blocksize) {
key = key + [0x00 * (blocksize - keyLngth)]; // keys shorter than blocksize are zero-padded
};
var o_key_pad = [0x5c * blocksize] ⊕ key; // Where blocksize is that of the underlying hash function
var i_key_pad = [0x36 * blocksize] ⊕ key; // Where ⊕ is exclusive or (XOR)
return hash(o_key_pad + hash(i_key_pad + message));
};
I guess wherever the pseudo Code states: hash(key)
one of the following hash functions: SHA-1, MD5, RIPEMD-128/160 needs to be used.
So I did a search on SHA-1 in JavaScript and found this:
http://www.movable-type.co.uk
Any info on how to create a HMAC value using Javascript would be greatly appreciated. I'll probably keep working on it, in the meantime. Even though it's Javascript, it's a Google .gs
Apps Script code file, which runs on the server.
回答1:
Apps Script has a built in Class Utility
for creating HMAC Sha256 signature or token:
Official Apps Script Documentation HMAC Sha256 signature
来源:https://stackoverflow.com/questions/22889270/generate-a-keyed-hash-value-using-the-hmac-method-with-google-apps-script