test.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. "use strict";
  2. // ./test.js
  3. var assert = require("assert")
  4. , Keygrip = require("./")
  5. , keylist, keys, hash, index
  6. // keygrip takes an array of keys. If missing or empty, it will throw.
  7. assert.throws(function() {
  8. keys = new Keygrip(/* empty list */);
  9. }, /must be provided/);
  10. // Randomly generated key - don't use this for something real. Don't be that person.
  11. keys = new Keygrip(['06ae66fdc6c2faf5a401b70e0bf885cb']);
  12. // .sign returns the hash for the first key
  13. // all hashes are SHA1 HMACs in url-safe base64
  14. hash = keys.sign("bieberschnitzel")
  15. assert.ok(/^[\w\-]{27}$/.test(hash))
  16. // but we're going to use our list.
  17. // (note that the 'new' operator is optional)
  18. keylist = ["SEKRIT3", "SEKRIT2", "SEKRIT1"] // keylist will be modified in place, so don't reuse
  19. keys = Keygrip(keylist)
  20. testKeygripInstance(keys);
  21. // now pass in a different hmac algorithm and encoding
  22. keylist = ["Newest", "AnotherKey", "Oldest"]
  23. keys = Keygrip(keylist, "sha256", "hex")
  24. testKeygripInstance(keys);
  25. function testKeygripInstance(keys) {
  26. hash = keys.sign("bieberschnitzel")
  27. // .index returns the index of the first matching key
  28. index = keys.index("bieberschnitzel", hash)
  29. assert.equal(index, 0)
  30. // .verify returns the a boolean indicating a matched key
  31. var matched = keys.verify("bieberschnitzel", hash)
  32. assert.ok(matched)
  33. index = keys.index("bieberschnitzel", "o_O")
  34. assert.equal(index, -1)
  35. // rotate a new key in, and an old key out
  36. keylist.unshift("SEKRIT4")
  37. keylist.pop()
  38. // if index > 0, it's time to re-sign
  39. index = keys.index("bieberschnitzel", hash)
  40. assert.equal(index, 1)
  41. hash = keys.sign("bieberschnitzel")
  42. }