HMAC Module

This hmac (About Modules) module implements a HMAC for Espruino.

Note: There was an older hmac module that depended on hashlib (a built-in module that is no longer included in Espruino). This new hmac has a different API that uses the crypto library.

How to use the module:

const HMAC = require('hmac');
var hmac = HMAC.SHA1(E.toArrayBuffer('my secret key'));
console.log(hmac.digest(E.toArrayBuffer('my message')));
// FixedSHA1 is faster than SHA1, but digested message must always be the same fixed length.
var hmacf = HMAC.FixedSHA1(E.toArrayBuffer('my secret key'), 2); // 2 bytes
console.log(hmacf.digest(E.toArrayBuffer('bb')));
console.log(hmacf.digest(E.toArrayBuffer('xx')));
const HMAC = require('hmac256');
var hmac = HMAC.SHA256(E.toArrayBuffer('my secret key'));
console.log(hmac.digest(E.toArrayBuffer('my message')));
// FixedSHA256 is faster than SHA256, but digested message must always be the same fixed length.
var hmacf = HMAC.FixedSHA256(E.toArrayBuffer('my secret key'), 2); // 2 bytes
console.log(hmacf.digest(E.toArrayBuffer('bb')));
console.log(hmacf.digest(E.toArrayBuffer('xx')));
// JWT
const HMAC = require('hmac256');
HmacSHA256 = function(token, secret) {
  var hmac = HMAC.SHA256(E.toArrayBuffer(secret));
  return btoa(String.fromCharCode.apply(null, hmac.digest(E.toArrayBuffer(token)))).replace(/=+$/, ''); 
};
var header = { "alg": "HS256", "typ": "JWT"};
var data = { "id": 1337,"username": "john.doe"};
var secret = "My very confidential secret!";
var encodedHeader = btoa(JSON.stringify(header));
var encodedData = btoa(JSON.stringify(data));
var token = encodedHeader + "." + encodedData;
var signature = HmacSHA256(token, secret);
var jwt = (token+'.'+signature);

Reference

// Returns an MAC instance using the given hash. Eg. HMAC(key, require('crypto').SHA1, 64, 20)
exports.HMAC = function (key, hash, blockSize, outputSize) { ... }

// Take a message as an arraybuffer or string, return an arraybuffer
undefined.prototype.digest = function (message) { ... }

// Take a message as an arraybuffer or string, return an arraybuffer
FixedHMAC.prototype.digest = function (message) { ... }

// Create a basic HMAC using SHA1
exports.SHA1 = function (key) { ... }

// FixedSHA1 is faster than SHA1, but digested message must always be the same fixed length.
exports.FixedSHA1 = function (key, messageSize) { ... }

// Create a basic HMAC using SHA256
exports.SHA256 = function (key) { ... }

// FixedSHA256 is faster than SHA256, but digested message must always be the same fixed length.
exports.FixedSHA256 = function (key, messageSize) { ... }

This page is auto-generated from GitHub. If you see any mistakes or have suggestions, please let us know.