Keygrip is a node.js module for signing and verifying data (such as cookies or URLs) through a rotating credential system, in which new server keys can be added and old ones removed regularly, without invalidating client credentials.
$ npm install keygrip
This creates a new Keygrip based on the provided keylist, an array of secret keys used for SHA1 HMAC digests.
keylist is obligatory.
hmacAlgorithm defaults to
encoding defaults to
Note that the
new operator is also optional, so all of the following will work when
Keygrip = require("keygrip"):
keys = "SEKRIT2" "SEKRIT1"keys =keys =keys =keys =keys =
The keylist is an array of all valid keys for signing, in descending order of freshness; new keys should be
unshifted into the array and old keys should be
The tradeoff here is that adding more keys to the keylist allows for more granular freshness for key validation, at the cost of a more expensive worst-case scenario for old or invalid hashes.
Keygrip keeps a reference to this array to automatically reflect any changes. This reference is stored using a closure to prevent external access.
This creates a SHA1 HMAC based on the first key in the keylist, and outputs it as a 27-byte url-safe base64 digest (base64 without padding, replacing
This loops through all of the keys currently in the keylist until the digest of the current key matches the given digest, at which point the current index is returned. If no key is matched,
-1 is returned.
The idea is that if the index returned is greater than
0, the data should be re-signed to prevent premature credential invalidation, and enable better performance for subsequent challenges.
index to return
true if the digest matches any existing keys, and
// ./test.jsvar assert =Keygrip =keylist keys hash index// but we're going to use our list.// (note that the 'new' operator is optional)keylist = "SEKRIT3" "SEKRIT2" "SEKRIT1"keys =// .sign returns the hash for the first key// all hashes are SHA1 HMACs in url-safe base64hash = keysassert// .index returns the index of the first matching keyindex = keysindex"bieberschnitzel" hashassert// .verify returns the a boolean indicating a matched keymatched = keysassertindex = keysindex"bieberschnitzel" "o_O"assert// rotate a new key in, and an old key outkeylistkeylist// if index > 0, it's time to re-signindex = keysindex"bieberschnitzel" hashasserthash = keys
Copyright (c) 2012 Jed Schmidt. See LICENSE.txt for details.
Send any questions or comments here.