Commit for version 1.1.2

This commit is contained in:
Guy Halford-Thompson 2011-10-02 18:08:30 -07:00
incheckning dac00027c4
7 ändrade filer med 1272 tillägg och 0 borttagningar

260
Readme.md Normal file
Visa fil

@ -0,0 +1,260 @@
# Node One Time Password library
Simple to use, fast, and with zero dependencies. The Node One Time Password library is fully compliant with [HOTP](http://tools.ietf.org/html/rfc4226) (counter based one time passwords) and [TOTP](http://tools.ietf.org/html/rfc6238) (time based one time passwords). It was designed to be used in conjunction with the [Google Authenticator](http://code.google.com/p/google-authenticator/) which has free apps for iOS, Android and BlackBerry.
# Installation
Via npm
$ npm install notp
Or... since there are no dependencies, you can simply download the files in ./lib and then just require as normal
$ require('./lib/nopt');
# Usage
IMPORTANT: The NOTP library accepts ASCII strings as keys, but the Google Authenticator app uses base32 encoded strings. If you wish to use this library in conjunction with the Google Authenticator app, then you need to convert the keys to base32 before entering them into the Google Authenticator app. NOTP provides helper functions for this.
var notp = require('notp'),
args = {};
//.... some initial login code, that receives the TOTP / HTOP
// token from the user
args.K = 'TOTP key for user... could be stored in DB';
args.P = 'User supplied TOTP value';
// Check TOTP is correct
notp.checkTOTP(
args,
function(err) { console.log('Oops, an error occured ' + err); },
function(login, sync) {
if(login) {
console.log('Token valid, sync value is ' + sync);
} else {
console.log('Token invalid');
}
}
);
# API
##notp.checkHOTP(args, err, cb)
Check a One Time Password based on a counter.
First argument of callback is true if password check is successful,
or false if check fails.
Second argument is the time step difference between the client and
the server. This argument is only passed if the password check is
successful.
Arguments:
args
K - Key for the one time password. This should be unique and secret for
every user as it is the seed used to calculate the HMAC
P - Passcode to validate.
W - The allowable margin for the counter. The function will check
W codes in the future against the provided passcode. Note,
it is the calling applications responsibility to keep track of
W and increment it for each password check, and also to adjust
it accordingly in the case where the client and server become
out of sync (second argument returns non zero).
E.g. if W = 100, and C = 5, this function will check the psscode
against all One Time Passcodes between 5 and 105.
Default - 50
C - Counter value. This should be stored by the application, must
be user specific, and be incremented for each request.
**Example**
notp.checkHOTP(
{
K : 'USER SPECIFIC KEY', // Should be ASCII string
P : 'USER SUPPLIED PASSCODE'
},
function(err) { console.log('Ooops ' + err); },
function(res, w) {
if(res) {
console.log('Check was successful, counter is out of sync by ' + w + ' steps');
} else {
console.log('Check was unsuccesful');
}
}
);
##notp.checkTOTP(args, err, cb)
Check a One Time Password based on a timer.
First argument of callback is true if password check is successful,
or false if check fails.
Second argument is the time step difference between the client and
the server. This argument is only passed if the password check is
successful.
Arguments:
args
K - Key for the one time password. This should be unique and secret for
every user as it is the seed used to calculate the HMAC
P - Passcode to validate.
W - The allowable margin for the counter. The function will check
W codes either side of the provided counter. Note,
it is the calling applications responsibility to keep track of
W and increment it for each password check, and also to adjust
it accordingly in the case where the client and server become
out of sync (second argument returns non zero).
E.g. if W = 5, and C = 1000, this function will check the psscode
against all One Time Passcodes between 995 and 1005.
Default - 6
T - The time step of the counter. This must be the same for
every request and is used to calculat C.
Default - 30
**Example**
notp.checkTOTP(
{
K : 'USER SPECIFIC KEY', // Should be ASCII string
P : 'USER SUPPLIED PASSCODE'
},
function(err) { console.log('Ooops ' + err); },
function(res, w) {
if(res) {
console.log('Check was successful, counter is out of sync by ' + w + ' steps');
} else {
console.log('Check was unsuccesful');
}
}
);
##notp.getHOTP(args, err, cb)
Generate a counter based One Time Password
First argument of callback is the value of the One Time Password
Arguments:
args
K - Key for the one time password. This should be unique and secret for
every user as it is the seed used to calculate the HMAC
C - Counter value. This should be stored by the application, must
be user specific, and be incremented for each request.
**Example**
notp.getHOTP(
{
K : 'USER SPECIFIC KEY', // Should be ASCII string
C : 5 // COUNTER VALUE
},
function(err) { console.log('Ooops ' + err); },
function(res) {
console.log('HOTP for supplied K and C values is ' + res);
}
);
##notp.getTOTP(args, err, cb)
NOTE: Base32 encoding and decoding provided by [Nibbler](http://www.tumuski.com/2010/04/nibbler) library
Gennerate a time based One Time Password
First argument of callback is the value of the One Time Password
Arguments:
args
K - Key for the one time password. This should be unique and secret for
every user as it is the seed used to calculate the HMAC
T - The time step of the counter. This must be the same for
every request and is used to calculat C.
Default - 30
**Example**
notp.getTOTP(
{
K : 'USER SPECIFIC KEY' // Should be ASCII string
},
function(err) { console.log('Ooops ' + err); },
function(res) {
console.log('TOTP for supplied K and C values is ' + res);
}
);
##notp.encBase32(str)
Helper function to convert a string to a base32 encoded string
Arguments:
str - String to encode
Returns: Base 32 encoded string
**Example**
var StringForGoogleAuthenticator = notp.encBase32('USER SPECIFIC KEY');
##notp.decBase32(b32)
Helper function to convert a base32 encoded string to an ascii string
Arguments:
b32 - String to decode
Returns: ASCII string
**Example**
var str = notp.decBase32('BASE32 ENCODED STRING');
# Developers
To run the tests, make sure you have [expresso](https://github.com/visionmedia/expresso) installed, and run it from the base directory. You should see some warnings when running the TOTP tests, this is normal and is a result of overriding the time settings. If anyone can come up with a better way of running the TOTP tests please let me know.
## License
(The MIT License)
Copyright (c) 2011 Guy Halford-Thompson <guy@cach.me>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

19
examples/TOTP.js Normal file
Visa fil

@ -0,0 +1,19 @@
var notp = require('../lib/notp'),
args = {
K : '12345678901234567890'
},
b32 = notp.encBase32(args.K);
console.log('Getting current counter value for K = 12345678901234567890');
console.log('This has a base32 value of ' + b32);
console.log('The base32 value should be entered in the Google Authenticator App');
console.log('');
notp.getTOTP(args,
function(err) { console.log(err); },
function(code) {
console.log('The current TOTP value is ' + code);
}
);

1
index.js Normal file
Visa fil

@ -0,0 +1 @@
module.exports = require('./lib/notp');

216
lib/external/nibbler.js vendored Normal file
Visa fil

@ -0,0 +1,216 @@
/*
Copyright (c) 2010 Thomas Peri
http://www.tumuski.com/
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true,
eqeqeq: true, plusplus: true, regexp: true, newcap: true, immed: true */
// (good parts minus bitwise and strict, plus white.)
/**
* Nibbler - Multi-Base Encoder
*
* version 2010-04-07
*
* Options:
* dataBits: The number of bits in each character of unencoded data.
* codeBits: The number of bits in each character of encoded data.
* keyString: The characters that correspond to each value when encoded.
* pad (optional): The character to pad the end of encoded output.
* arrayData (optional): If truthy, unencoded data is an array instead of a string.
*
* Example:
*
* var base64_8bit = new Nibbler({
* dataBits: 8,
* codeBits: 6,
* keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
* pad: '='
* });
* base64_8bit.encode("Hello, World!"); // returns "SGVsbG8sIFdvcmxkIQ=="
* base64_8bit.decode("SGVsbG8sIFdvcmxkIQ=="); // returns "Hello, World!"
*
* var base64_7bit = new Nibbler({
* dataBits: 7,
* codeBits: 6,
* keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
* pad: '='
* });
* base64_7bit.encode("Hello, World!"); // returns "kZdmzesQV9/LZkQg=="
* base64_7bit.decode("kZdmzesQV9/LZkQg=="); // returns "Hello, World!"
*
*/
var Nibbler = function (options) {
var construct,
// options
pad, dataBits, codeBits, keyString, arrayData,
// private instance variables
mask, group, max,
// private methods
gcd, translate,
// public methods
encode, decode;
// pseudo-constructor
construct = function () {
var i, mag, prev;
// options
pad = options.pad || '';
dataBits = options.dataBits;
codeBits = options.codeBits;
keyString = options.keyString;
arrayData = options.arrayData;
// bitmasks
mag = Math.max(dataBits, codeBits);
prev = 0;
mask = [];
for (i = 0; i < mag; i += 1) {
mask.push(prev);
prev += prev + 1;
}
max = prev;
// ouput code characters in multiples of this number
group = dataBits / gcd(dataBits, codeBits);
};
// greatest common divisor
gcd = function (a, b) {
var t;
while (b !== 0) {
t = b;
b = a % b;
a = t;
}
return a;
};
// the re-coder
translate = function (input, bitsIn, bitsOut, decoding) {
var i, len, chr, byteIn,
buffer, size, output,
write;
// append a byte to the output
write = function (n) {
if (!decoding) {
output.push(keyString.charAt(n));
} else if (arrayData) {
output.push(n);
} else {
output.push(String.fromCharCode(n));
}
};
buffer = 0;
size = 0;
output = [];
len = input.length;
for (i = 0; i < len; i += 1) {
// the new size the buffer will be after adding these bits
size += bitsIn;
// read a character
if (decoding) {
// decode it
chr = input.charAt(i);
byteIn = keyString.indexOf(chr);
if (chr === pad) {
break;
} else if (byteIn < 0) {
throw 'the character "' + chr + '" is not a member of ' + keyString;
}
} else {
if (arrayData) {
byteIn = input[i];
} else {
byteIn = input.charCodeAt(i);
}
if ((byteIn | max) !== max) {
throw byteIn + " is outside the range 0-" + max;
}
}
// shift the buffer to the left and add the new bits
buffer = (buffer << bitsIn) | byteIn;
// as long as there's enough in the buffer for another output...
while (size >= bitsOut) {
// the new size the buffer will be after an output
size -= bitsOut;
// output the part that lies to the left of that number of bits
// by shifting the them to the right
write(buffer >> size);
// remove the bits we wrote from the buffer
// by applying a mask with the new size
buffer &= mask[size];
}
}
// If we're encoding and there's input left over, pad the output.
// Otherwise, leave the extra bits off, 'cause they themselves are padding
if (!decoding && size > 0) {
// flush the buffer
write(buffer << (bitsOut - size));
// add padding keyString for the remainder of the group
len = output.length % group;
for (i = 0; i < len; i += 1) {
output.push(pad);
}
}
// string!
return (arrayData && decoding) ? output : output.join('');
};
/**
* Encode. Input and output are strings.
*/
encode = function (input) {
return translate(input, dataBits, codeBits, false);
};
/**
* Decode. Input and output are strings.
*/
decode = function (input) {
return translate(input, codeBits, dataBits, true);
};
this.encode = encode;
this.decode = decode;
construct();
};
// For nodejs
module.exports = Nibbler;

376
lib/notp.js Normal file
Visa fil

@ -0,0 +1,376 @@
/*
* Requires
*/
var crypto = require('crypto'),
base32 = require('./external/nibbler');
/*
* Export module as new Notp instance
*/
module.exports = new Notp();
/*
* Constructor function.
*
* Builds th base32 object
*/
function Notp() {
base32 = new base32(
{
dataBits: 8,
codeBits: 5,
keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
pad: '='
}
);
}
/*
* Check a One Time Password based on a counter.
*
* First argument of callback is true if password check is successful,
* or false if check fails.
*
* Second argument is the time step difference between the client and
* the server. This argument is only passed if the password check is
* successful.
*
* Arguments:
*
* args
* K - Key for the one time password. This should be unique and secret for
* every user as it is the seed used to calculate the HMAC
*
* P - Passcode to validate.
*
* W - The allowable margin for the counter. The function will check
* W codes in the future against the provided passcode. Note,
* it is the calling applications responsibility to keep track of
* W and increment it for each password check, and also to adjust
* it accordingly in the case where the client and server become
* out of sync (second argument returns non zero).
* E.g. if W = 100, and C = 5, this function will check the psscode
* against all One Time Passcodes between 5 and 105.
*
* Default - 50
*
* C - Counter value. This should be stored by the application, must
* be user specific, and be incremented for each request.
*
*/
Notp.prototype.checkHOTP = function(args, err, cb) {
var hmac,
digest,
offset, h, v, p = 6, b,
i,
K = args.K || "",
W = args.W || 50,
C = args.C || 0,
P = args.P || "";
// Initiate the HMAC
hmac = crypto.createHmac('SHA1', new Buffer(K))
// Now loop through from C to C + W to determine if there is
// a correct code
for(i = C; i <= C+W; i++) {
if(this._calcHMAC(K,i) === P) {
// We have found a matching code, trigger callback
// and pass offset
cb(true, i - C);
return;
}
}
// If we get to here then no codes have matched, return false
cb(false);
return;
};
/*
* Check a One Time Password based on a timer.
*
* First argument of callback is true if password check is successful,
* or false if check fails.
*
* Second argument is the time step difference between the client and
* the server. This argument is only passed if the password check is
* successful.
*
* Arguments:
*
* args
* K - Key for the one time password. This should be unique and secret for
* every user as it is the seed used to calculate the HMAC
*
* P - Passcode to validate.
*
* W - The allowable margin for the counter. The function will check
* W codes either side of the provided counter. Note,
* it is the calling applications responsibility to keep track of
* W and increment it for each password check, and also to adjust
* it accordingly in the case where the client and server become
* out of sync (second argument returns non zero).
* E.g. if W = 5, and C = 1000, this function will check the psscode
* against all One Time Passcodes between 995 and 1005.
*
* Default - 6
*
* T - The time step of the counter. This must be the same for
* every request and is used to calculat C.
*
* Default - 30
*
*/
Notp.prototype.checkTOTP = function(args, err, cb) {
var hmac,
digest,
offset, h, v, p = 6, b,
C,i,
K = args.K || "",
W = args.W || 6,
T = args.T || 30,
P = args.P || "",
_t;
if(args._t) {
// Time has been overwritten.
console.log('#####################################');
console.log('# NOTE: TOTP TIME VARIABLE HAS BEEN #');
console.log('# OVERWRITTEN. THIS SHOULD ONLY BE #');
console.log('# USED FOR TEST PURPOSES. #');
console.log('#####################################');
_t = args._t;
} else {
_t = new Date().getTime();
}
// Initiate the HMAC
hmac = crypto.createHmac('SHA1', new Buffer(K))
// Determine the value of the counter, C
// This is the number of time steps in seconds since T0
C = Math.floor((_t / 1000) / T);
// Now loop through from C - W to C + W and check to see
// if we have a valid code in that time line
for(i = C-W; i <= C+W; i++) {
if(this._calcHMAC(K,i) === P) {
// We have found a matching code, trigger callback
// and pass offset
cb(true, i-C);
return;
}
}
// If we get to here then no codes have matched, return false
cb(false);
return;
};
/*
* Gennerate a counter based One Time Password
*
* First argument of callback is the value of the One Time Password
*
* Arguments:
*
* args
* K - Key for the one time password. This should be unique and secret for
* every user as it is the seed used to calculate the HMAC
*
* C - Counter value. This should be stored by the application, must
* be user specific, and be incremented for each request.
*
*/
Notp.prototype.getHOTP = function(args, err, cb) {
var hmac,
digest,
offset, h, v, p = 6, b,
i,
K = args.K || "",
C = args.C || 0,
// Initiate the HMAC
hmac = crypto.createHmac('SHA1', new Buffer(K))
cb(this._calcHMAC(K,C));
};
/*
* Gennerate a time based One Time Password
*
* First argument of callback is the value of the One Time Password
*
* Arguments:
*
* args
* K - Key for the one time password. This should be unique and secret for
* every user as it is the seed used to calculate the HMAC
*
* T - The time step of the counter. This must be the same for
* every request and is used to calculat C.
*
* Default - 30
*
*/
Notp.prototype.getTOTP = function(args, err, cb) {
var hmac,
digest,
offset, h, v, p = 6, b,
C,i,
K = args.K || "",
T = args.T || 30,
_t;
if(args._t) {
// Time has been overwritten.
console.log('#####################################');
console.log('# NOTE: TOTP TIME VARIABLE HAS BEEN #');
console.log('# OVERWRITTEN. THIS SHOULD ONLY BE #');
console.log('# USED FOR TEST PURPOSES. #');
console.log('#####################################');
_t = args._t;
} else {
_t = new Date().getTime();
}
// Initiate the HMAC
hmac = crypto.createHmac('SHA1', new Buffer(K))
// Determine the value of the counter, C
// This is the number of time steps in seconds since T0
C = Math.floor((_t / 1000) / T);
cb(this._calcHMAC(K,C));
};
/*
* Helper function to convert a string to a base32 encoded string
*
* Arguments:
*
* str - String to encode
*
* Returns: Base 32 encoded string
*/
Notp.prototype.encBase32 = function(str) {
return base32.encode(str);
};
/*
* Helper function to convert a base32 encoded string to an ascii string
*
* Arguments:
*
* b32 - String to decode
*
* Returns: ASCII string
*/
Notp.prototype.decBase32 = function(b32) {
return base32.decode(b32);
};
/******************************************************************
* NOTE: Any functions below this line are private and therefore *
* may change without providing backwards compatibility with *
* previous versions. You should not call the functions below *
* directly. *
*******************************************************************/
/*
* Private functon to calculate an HMAC.
*
* Arguments
*
* K - Key value
* C - Counter value
*
* Returns - truncated HMAC
*/
Notp.prototype._calcHMAC = function(K, C) {
var hmac = crypto.createHmac('SHA1', new Buffer(K)),
digest,
offset, h, v, p = 6, b;
// Create the byte array
b = new Buffer(this._intToBytes(C)),
// Update the HMAC witht he byte array
hmac.update(b);
// Diget the HMAC
digest = hmac.digest('hex');
// Get byte array
h = this._hexToBytes(digest);
// Truncate
offset = h[19] & 0xf;
v = (h[offset] & 0x7f) << 24 | (h[offset + 1] & 0xff) << 16 | (h[offset + 2] & 0xff) << 8 | (h[offset + 3] & 0xff);
v = "" + v;
v = v.substr(v.length - p, p);
return v;
};
/*
* Private function to convert an integer to a byte array
*
* Arguments
*
* num - Integer
*
* Returns - byte array
*/
Notp.prototype._intToBytes = function(num) {
var bytes = [],
i;
for(i=7;i>=0;i--) {
bytes[i] = num & (255);
num = num >> 8;
}
return bytes;
};
/*
* Private function to convert a hex value to a byte array
*
* Arguments
*
* hex - Hex value
*
* Returns - byte array
*/
Notp.prototype._hexToBytes = function(hex) {
for(var bytes = [], c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
};

22
package.json Normal file
Visa fil

@ -0,0 +1,22 @@
{
"author": "Guy Halford-Thompson <guy@cach.me> (http://cach.me)",
"name": "notp",
"description": "Node One Time Password library, supports HOTP, TOTP and works with Google Authenticator",
"version": "1.1.2",
"homepage": "https://github.com/guyht/notp",
"repository": {
"type": "git",
"url": "git://github.com/guyht/notp.git"
},
"main": "index.js",
"scripts": {
"test": "expresso"
},
"engines": {
"node": "~v0.4.10"
},
"dependencies": {},
"devDependencies": {
"expresso" : "0.9.0"
}
}

378
test/notp.js Normal file
Visa fil

@ -0,0 +1,378 @@
/*
* Notp test suite
*/
var notp = require('../lib/notp');
/*
* Test HOTP. Uses test values from RFC 4226
*
*
* The following test data uses the ASCII string
* "12345678901234567890" for the secret:
*
* Secret = 0x3132333435363738393031323334353637383930
*
* Table 1 details for each count, the intermediate HMAC value.
*
* Count Hexadecimal HMAC-SHA-1(secret, count)
* 0 cc93cf18508d94934c64b65d8ba7667fb7cde4b0
* 1 75a48a19d4cbe100644e8ac1397eea747a2d33ab
* 2 0bacb7fa082fef30782211938bc1c5e70416ff44
* 3 66c28227d03a2d5529262ff016a1e6ef76557ece
* 4 a904c900a64b35909874b33e61c5938a8e15ed1c
* 5 a37e783d7b7233c083d4f62926c7a25f238d0316
* 6 bc9cd28561042c83f219324d3c607256c03272ae
* 7 a4fb960c0bc06e1eabb804e5b397cdc4b45596fa
* 8 1b3c89f65e6c9e883012052823443f048b4332db
* 9 1637409809a679dc698207310c8c7fc07290d9e5
*
* Table 2 details for each count the truncated values (both in
* hexadecimal and decimal) and then the HOTP value.
*
* Truncated
* Count Hexadecimal Decimal HOTP
* 0 4c93cf18 1284755224 755224
* 1 41397eea 1094287082 287082
* 2 82fef30 137359152 359152
* 3 66ef7655 1726969429 969429
* 4 61c5938a 1640338314 338314
* 5 33c083d4 868254676 254676
* 6 7256c032 1918287922 287922
* 7 4e5b397 82162583 162583
* 8 2823443f 673399871 399871
* 9 2679dc69 645520489 520489
*
*
* see http://tools.ietf.org/html/rfc4226
*/
exports.testHOTP = function(beforeExit, assert) {
var n = 0,
args = {
W : 0,
K : '12345678901234567890'
},
HOTP = ['755224', '287082','359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489'];
// Check for failure
args.C = 0;
args.P = 'WILLNOTPASS';
notp.checkHOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, false, 'Should not pass');
n++;
}
);
// Check for passes
for(i=0;i<HOTP.length;i++) {
args.C = i;
args.P = HOTP[i];
notp.checkHOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, true, 'Should pass');
assert.eql(w, 0, 'Should be in sync');
n++;
}
);
}
beforeExit(function() {
assert.equal(HOTP.length + 1, n, 'All tests should have been run');
});
};
/*
* Test TOTP using test vectors from TOTP RFC.
*
* see http://tools.ietf.org/id/draft-mraihi-totp-timebased-06.txt
*/
exports.testTOTP = function(beforeExit, assert) {
var n = 0,
args = {
W : 0,
K : '12345678901234567890'
};
// Check for failure
args.T = 0;
args.P = 'WILLNOTPASS';
notp.checkTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, false, 'Should not pass');
n++;
}
);
// Check for test vector at 59s
args._t = 59*1000;
args.P = '287082';
notp.checkTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, true, 'Should pass');
assert.eql(w, 0, 'Should be in sync');
n++;
}
);
// Check for test vector at 1234567890
args._t = 1234567890*1000;
args.P = '005924';
notp.checkTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, true, 'Should pass');
assert.eql(w, 0, 'Should be in sync');
n++;
}
);
// Check for test vector at 1111111109
args._t = 1111111109*1000;
args.P = '081804';
notp.checkTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, true, 'Should pass');
assert.eql(w, 0, 'Should be in sync');
n++;
}
);
// Check for test vector at 2000000000
args._t = 2000000000*1000;
args.P = '279037';
notp.checkTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, true, 'Should pass');
assert.eql(w, 0, 'Should be in sync');
n++;
}
);
beforeExit(function() {
assert.equal(5, n, 'All tests should have been run');
});
};
/*
* Check for codes that are out of sync
* We are going to use a value of C = 1 and test against
* a code for C = 9
*/
exports.testHOTPOutOfSync = function(beforeExit, assert) {
var n = 0,
args = {
K : '12345678901234567890',
P : '520489',
C : 1
};
// Check that the test should fail for W < 8
args.W = 7;
notp.checkHOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, false, 'Should not pass for value of W < 8');
n++;
}
);
// Check that the test should pass for W >= 9
args.W = 8;
notp.checkHOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, true, 'Should pass for value of W >= 9');
n++;
}
);
beforeExit(function() {
assert.equal(2, n, 'All tests should have been run');
});
};
/*
* Check for codes that are out of sync
* We are going to use a value of T = 1999999909 (91s behind 2000000000)
*/
exports.testTOTPOutOfSync = function(beforeExit, assert) {
var n = 0,
args = {
K : '12345678901234567890',
P : '279037',
_t : 1999999909*1000
};
// Check that the test should fail for W < 2
args.W = 2;
notp.checkTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, false, 'Should not pass for value of W < 3');
n++;
}
);
// Check that the test should pass for W >= 3
args.W = 3;
notp.checkTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, true, 'Should pass for value of W >= 3');
n++;
}
);
beforeExit(function() {
assert.equal(2, n, 'All tests should have been run');
});
};
/*
* Test getHOTP function. Uses same test values as for checkHOTP
*/
exports.testGetHOTP = function(beforeExit, assert) {
var n = 0,
args = {
W : 0,
K : '12345678901234567890'
},
HOTP = ['755224', '287082','359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489'];
// Check for passes
for(i=0;i<HOTP.length;i++) {
args.C = i;
notp.getHOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret) {
assert.eql(ret, HOTP[i], 'HTOP value should be correct');
n++;
}
);
}
beforeExit(function() {
assert.equal(HOTP.length, n, 'All tests should have been run');
});
};
/*
* Test getTOTP function. Uses same test values as for checkTOTP
*/
exports.testGetTOTP = function(beforeExit, assert) {
var n = 0,
args = {
W : 0,
K : '12345678901234567890'
};
// Check for test vector at 59s
args._t = 59*1000;
notp.getTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, '287082', 'TOTP values should match');
n++;
}
);
// Check for test vector at 1234567890
args._t = 1234567890*1000;
notp.getTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, '005924', 'TOTP values should match');
n++;
}
);
// Check for test vector at 1111111109
args._t = 1111111109*1000;
notp.getTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, '081804', 'TOTP values should match');
n++;
}
);
// Check for test vector at 2000000000
args._t = 2000000000*1000;
notp.getTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, '279037', 'TOTP values should match');
n++;
}
);
beforeExit(function() {
assert.equal(4, n, 'All tests should have been run');
});
};
/*
* Test encode to base32
*/
exports.testEncodeToBase32 = function(beforeExit, assert) {
assert.eql(notp.encBase32('12345678901234567890'), 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ');
};
/*
* Test decode base32
*/
exports.testDecodeFromBase32 = function(beforeExit, assert) {
assert.eql(notp.decBase32('GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'), '12345678901234567890');
};