[Pkg-javascript-commits] [node-keygrip] 04/68: first code push

Andrew Kelley andrewrk-guest at moszumanska.debian.org
Fri Jun 27 22:13:23 UTC 2014


This is an automated email from the git hooks/post-receive script.

andrewrk-guest pushed a commit to branch master
in repository node-keygrip.

commit 9cfd5bc086da2f7f9fed2e340a4835384590e23e
Author: Jed Schmidt <tr at nslator.jp>
Date:   Fri Feb 25 15:35:53 2011 +0900

    first code push
---
 index.js       |  1 +
 lib/keygrip.js | 35 +++++++++++++++++++++++++++++++++++
 test.js        | 25 +++++++++++++++++++++++++
 3 files changed, 61 insertions(+)

diff --git a/index.js b/index.js
new file mode 100644
index 0000000..2d8e632
--- /dev/null
+++ b/index.js
@@ -0,0 +1 @@
+module.exports = require( "./lib/keygrip" )
\ No newline at end of file
diff --git a/lib/keygrip.js b/lib/keygrip.js
new file mode 100644
index 0000000..c6ea0a6
--- /dev/null
+++ b/lib/keygrip.js
@@ -0,0 +1,35 @@
+crypto = require( "crypto" )
+
+function KeyGrip( keys ) {
+  if ( !( this instanceof KeyGrip ) ) return new KeyGrip( keys )
+  
+  if ( !keys || !keys.length ) {
+    console.warn( "No keys specified, using defaults instead." )
+    keys = [ "I'm stupid" ]
+  }
+  
+  function sign( data, key ) {
+    return crypto
+      .createHmac( "sha1", key )
+      .update( data ).digest( "base64" )
+      .replace( /\/|\+|=/g, function( x ) {
+        return ({ "/": "_", "+": "-", "=": "" })[ x ]  
+      })
+  }
+
+  this.sign = function( data ){ return sign( data, keys[ 0 ] ) }
+
+  this.verify = function( data, key ) {
+    for ( var i = 0, l = keys.length; i < l; i++ ) {
+      if ( key === sign( data, keys[ i ] ) ) return i
+    }
+    
+    return -1
+  }
+}
+
+KeyGrip.sign = KeyGrip.verify = function() {
+  throw "Usage: require( 'keygrip' )( <array-of-keys> )"
+}
+
+module.exports = KeyGrip
\ No newline at end of file
diff --git a/test.js b/test.js
new file mode 100644
index 0000000..dfde803
--- /dev/null
+++ b/test.js
@@ -0,0 +1,25 @@
+var assert = require( "assert" )
+  , secrets = [ "SEKRIT3", "SEKRIT2", "SEKRIT1" ]
+  , keys = require( "./" )( secrets )
+  , hash, index
+
+// .sign returns the hash for the first key
+// all hashes are SHA1 HMACs in url-safe base64
+hash = keys.sign( "bieberschnitzel" )
+assert.equal( hash, "4O9Lm0qQPd7_pViJBPKA_8jYwb8" )
+
+// .verify returns the index of the first matching key
+index = keys.verify( "bieberschnitzel", hash )
+assert.equal( index, 0 )
+
+index = keys.verify( "bieberschnitzel", "o_O" )
+assert.equal( index, -1 )
+
+// rotate a new key in, and an old key out
+secrets.unshift( "SEKRIT4" )
+secrets.pop()
+
+// if index > 0, it's time to re-sign
+index = keys.verify( "bieberschnitzel", hash )
+assert.equal( index, 1 )
+hash = keys.sign( "bieberschnitzel" )
\ No newline at end of file

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/node-keygrip.git



More information about the Pkg-javascript-commits mailing list