I’m trying to do a SHA256 hash of a string using the HMAC method, using my secret key as the hash key.
scopes.svyCrypto.getSHA256() doesn’t take a secret key as an argument.
scopes.svyCrypto.getHash() also doesn’t take a secret key as an argument
scopes.svyCrypto.createOptions() allows a key and algorithm to be set, but I get an error Unsupported Algorithm: SHA-256
function encode(key, data) {
var sha256_HMAC = javax.crypto.Mac.getInstance("HmacSHA256");
var secret_key = new javax.crypto.spec.SecretKeySpec(getStringBytes(key), "HmacSHA256");
sha256_HMAC.init(secret_key);
var encodedVal = org.apache.commons.codec.binary.Hex.encodeHexString(sha256_HMAC.doFinal(getStringBytes(data)));
return encodedVal;
}
In case you need a base64 encoded result you can use this variant:
function hash_hmac(key, data) {
var sha256_HMAC = javax.crypto.Mac.getInstance("HmacSHA256")
var secret_key = new javax.crypto.spec.SecretKeySpec(utils.stringToBytes(key), "HmacSHA256")
sha256_HMAC.init(secret_key)
var encodedVal = utils.bytesToBase64((sha256_HMAC.doFinal(utils.stringToBytes(data))))
return encodedVal
}