Compare commits

..

No commits in common. "master" and "2.0.0" have entirely different histories.

12 changed files with 464 additions and 456 deletions

28
.gitignore vendored
View File

@ -1,29 +1 @@
bower_components
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directory
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
node_modules

View File

@ -1,6 +1,4 @@
language: node_js
node_js:
- "0.6"
- "0.8"
- "0.10"
- "0.11"
- 0.4
- 0.6

View File

@ -1,60 +0,0 @@
# You might be in the wrong place
You probably want [Authenticator](https://github.com/Daplie/browser-authenticator).
# Browser One Time Password library (JavaScript)
(aka botp / totp.js / hotp.js)
(forked from [Node One Time Password](https://github.com/guyht/notp))
Simple to use, fast, and with zero dependencies\*. The Browser 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).
\* requires [forge](https://github.com/digitalbazaar/forge) for window.sha1Hmac shim in older browsers and [es6-promise](https://github.com/jakearchibald/es6-promise) for ancient browsers.
It can be used in conjunction with the [Authy](https://www.authy.com/personal/), [Google Authenticator](https://github.com/google/google-authenticator/), and [Microsoft Authenticator](https://www.microsoft.com/en-us/store/apps/authenticator/9wzdncrfj3rj), and [GAuth](https://5apps.com/gbraad/gauth) which have free apps for iOS, Android, BlackBerry, OS X, Linux, Windows, and Chrome.
Browser One Time Password library, supports HOTP, TOTP and works with Google Authenticator • forked from https://github.com/guyht/notp
# Installation
```
bower install botp
```
# Usage
```javascript
(function () {
'use strict';
var botp = window.botp;
// this might be used on account creation to create the QR code and verify the token in the browser.
var key = 'secret key for user... could be stored in DB'; // Uint8Array
var token = 'user supplied one time use token'; // 890123
// Check TOTP is correct (HOTP if hotp pass type)
botp.totp.verify(token, key).then(function (login) {
// invalid token if login is null
if (!login) {
console.log('Token invalid');
return;
}
// valid token
console.log('Token valid, sync value is %s', login.delta);
});
}());
```
# API
See <https://github.com/guyht/notp#api>
* botp.totp.gen(keyByteArray) => (promise) tokenArray
* botp.totp.verify(tokenByteArray, keyByteArray) => (promise) delta or null
* botp.hotp.gen(keyByteArray) => (promise) tokenArray
* botp.hotp.verify(tokenByteArray, keyByteArray) => (promise) delta or null

132
Readme.md Normal file
View File

@ -0,0 +1,132 @@
[![Build Status](https://secure.travis-ci.org/guyht/notp.png)](http://travis-ci.org/guyht/notp)
# 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 can 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
```
npm install notp
```
# Usage
```javascript
var notp = require('notp');
//.... some initial login code, that receives the user details and TOTP / HOTP token
var key = 'secret key for user... could be stored in DB';
var token = 'user supplied one time use token';
// Check TOTP is correct (HOTP if hotp pass type)
var login = notp.totp.verify(token, key);
// invalid token if login is null
if (!login) {
return console.log('Token invalid');
}
// valid token
console.log('Token valid, sync value is %s', login.delta);
```
## Google Authenticator
[Google authenticator](https://code.google.com/p/google-authenticator/) requires that keys be base32 encoded before being used. This includes manual entry into the app as well as preparing a QR code URI.
To base32 encode a utf8 key you can use the `thirty-two` module.
```javascript
var base32 = require('thirty-two');
var key = 'secret key for the user';
// encoded will be the secret key, base32 encoded
var encoded = base32.encode(key);
// to create a URI for a qr code (change totp to hotp is using hotp)
var uri = 'otpauth://totp/somelabel?secret=' + encoded;
```
Note: If your label has spaces or other invalid uri characters you will need to encode it accordingly using `encodeURIComponent` More details about the uri key format can be found on the [google auth wiki](https://code.google.com/p/google-authenticator/wiki/KeyUriFormat)
# API
##hotp.verify(token, key, opt)
Check a counter based one time password for validity.
Returns null if token is not valid for given key and options.
Returns an object `{delta: #}` if the token is valid. `delta` is the count skew between client and server.
### opt
**window**
> The allowable margin for the counter. The function will check `window` codes in the future against the provided token.
> i.e. if `window = 100` and `counter = 5` all tokens between 5 and 105 will be checked against the supplied token
> Default - 50
**counter**
> Counter value. This should be stored by the application on a per user basis. It is up to the application to track and increment this value as needed. It is also up to the application to increment this value if there is a skew between the client and server (`delta`)
##totp.verify(token, key, opt)
Check a time based one time password for validity
Returns null if token is not valid for given key and options.
Returns an object `{delta: #}` if the token is valid. `delta` is the count skew between client and server.
### opt
**window**
> The allowable margin for the counter. The function will check `window` codes in the future against the provided token.
> i.e. if `window = 5` and `counter = 1000` all tokens between 995 and 1005 will be checked against the supplied token
> Default - 6
**time**
> The time step of the counter. This must be the same for every request and is used to calculate C.
> Default - 30
##hotp.gen(key, opt)
Return a counter based one time password
### opt
**counter**
> Counter value. This should be stored by the application, must be user specific, and be incremented for each request.
##totp.gen(key, opt)
Return a time based one time password
### opt
**time**
> The time step of the counter. This must be the same for every request and is used to calculate C.
> Default - 30
# Migrating from 1.x to 2.x
## Removed
The `encBase32` and `decBase32` methods have been removed. If you wish to encode/decode base32 you should install a module to do so. We recommend the `thirty-two` npm module.
## Changed
All of the APIs have been changed to return values directly instead of using callbacks. This reflects the fact that the functions are actually synchronous and perform no I/O.
Some of the required arguments to the functions have also been removed from the `args` parameter and are passed as separate function parameters. See the above API docs for details.
* `notp.checkHOTP(args, err, cb)` -> `notp.hotp.verify(token, key, opt)`
* `notp.checkTOTP(args, err, cb)` -> `notp.totp.verify(token, key, opt)`
* `notp.getHOTP(args, err, cb)` -> `notp.gotp.gen(key, opt)`
* `notp.getTOTP(args, err, cb)` -> `notp.totp.gen(key, opt)`
## Args
The argument names have also changed to better describe the purpose of the argument.
* `K` -> no longer in args/opt but passed directly as a function argument
* `P` -> no longer in args/opt but passed directly as a function argument
* `W` -> `window`
* `C` -> `counter`
* `T` -> `time`

View File

@ -1,37 +0,0 @@
{
"name": "botp",
"main": "index.js",
"version": "3.0.2",
"homepage": "https://github.com/Daplie/botp",
"authors": [
"AJ ONeal <aj@daplie.com>",
"Guy Halford-Thompson <guy@guy.ht>"
],
"description": "JavaScript One Time Password library, supports HOTP, TOTP and works with all Authenticator apps.",
"moduleType": [
"globals",
"node"
],
"keywords": [
"totp",
"hotp",
"botp",
"notp",
"time",
"based",
"one",
"time",
"password",
"browser",
"javascript"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
],
"dependencies": {}
}

19
examples/TOTP.js Normal file
View File

@ -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);
}
);

169
index.js
View File

@ -1,43 +1,5 @@
(function (exports, TEST) {
'use strict';
var crypto;
var sha1Hmac = exports.sha1Hmac || function (key, bytes) {
if (!crypto) { crypto = require('crypto'); }
var hmac = crypto.createHmac('sha1', new Buffer(key));
// Update the HMAC with the byte array
return hmac.update(new Buffer(bytes)).digest('hex');
};
/**
* convert an integer to a byte array
* @param {Integer} num
* @return {Array} bytes
*/
function intToBytes(num) {
var bytes = [];
for(var i=7 ; i>=0 ; --i) {
bytes[i] = num & (255);
num = num >> 8;
}
return bytes;
}
/**
* convert a hex value to a byte array
* @param {String} hex string of hex to convert to a byte array
* @return {Array} bytes
*/
function hexToBytes(hex) {
var bytes = [];
for(var c = 0, C = hex.length; c < C; c += 2) {
bytes.push(parseInt(hex.substr(c, 2), 16));
}
return bytes;
}
var crypto = require('crypto');
var hotp = {};
@ -50,19 +12,26 @@ var hotp = {};
*
* args
* key - Key for the one time password. This should be unique and secret for
* every user as this is the seed that is used to calculate the HMAC
* every user as it is the seed used to calculate the HMAC
*
* counter - Counter value. This should be stored by the application, must
* be user specific, and be incremented for each request.
*
*/
hotp.gen = function(key, opt) {
key = key || '';
opt = opt || {};
var key = key || '';
var counter = opt.counter || 0;
var p = 6;
// Create the byte array
return sha1Hmac(key, intToBytes(counter)).then(function (digest) {
var b = new Buffer(intToBytes(counter));
var hmac = crypto.createHmac('SHA1', new Buffer(key));
// Update the HMAC witht he byte array
var digest = hmac.update(b).digest('hex');
// Get byte array
var h = hexToBytes(digest);
@ -73,10 +42,9 @@ hotp.gen = function(key, opt) {
(h[offset + 2] & 0xff) << 8 |
(h[offset + 3] & 0xff);
v = (v % 1000000) + '';
v = v + '';
return new Array(7-v.length).join('0') + v;
});
return v.substr(v.length - p, p);
};
/**
@ -94,12 +62,12 @@ hotp.gen = function(key, opt) {
* token - Passcode to validate.
*
* window - The allowable margin for the counter. The function will check
* 'W' codes in the future against the provided passcode. Note,
* 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
* 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 passcode
* 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
@ -109,46 +77,22 @@ hotp.gen = function(key, opt) {
*
*/
hotp.verify = function(token, key, opt) {
opt = opt || {};
var window = opt.window || 50;
var counter = opt.counter || 0;
var i = counter - window;
var len = counter + window;
// Now loop through from C to C + W to determine if there is
// a correct code
function check(t) {
opt.counter = i + 1;
if (!t) {
return null;
}
if (i > len) {
return null;
}
if(t === token) {
for(var i = counter; i <= counter + window; ++i) {
opt.counter = i;
if(this.gen(key, opt) === token) {
// We have found a matching code, trigger callback
// and pass offset
return i;
}
// TODO count 0, -1, 1, -2, 2, ... instead of -2, -1, 0, 1, ...
i += 1;
return hotp.gen(key, opt).then(check);
}
opt.counter = i;
return hotp.gen(key, opt).then(check).then(function (i) {
if('number' === typeof i) {
return { delta: i - counter };
}
}
// If we get to here then no codes have matched, return null
return null;
});
// If we get to here then no codes have matched, return false
return false;
};
var totp = {};
@ -171,15 +115,16 @@ var totp = {};
*
*/
totp.gen = function(key, opt) {
opt = opt || {};
var time = opt.time || 30;
var _t = Date.now();
var _t = new Date().getTime();;
// Time has been overwritten.
if(opt._t) {
if(!TEST) {
console.warn('Overwriting time in non-test environment!');
}
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 = opt._t;
}
@ -205,12 +150,12 @@ totp.gen = function(key, opt) {
* token - Passcode to validate.
*
* window - The allowable margin for the counter. The function will check
* 'W' codes either side of the provided counter. Note,
* 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
* 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 passcode
* 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
@ -222,15 +167,16 @@ totp.gen = function(key, opt) {
*
*/
totp.verify = function(token, key, opt) {
opt = opt || {};
var time = opt.time || 30;
var _t = Date.now();
var _t = new Date().getTime();
// Time has been overwritten.
if(opt._t) {
if(!TEST) {
console.warn('Overwriting time in non-test environment!');
}
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 = opt._t;
}
@ -241,9 +187,36 @@ totp.verify = function(token, key, opt) {
return hotp.verify(token, key, opt);
};
exports.hotp = hotp;
exports.totp = totp;
}(
'undefined' !== typeof window ? window : module.exports
, 'undefined' !== typeof process ? process.env.NODE_ENV : false
));
module.exports.hotp = hotp;
module.exports.totp = totp;
/**
* convert an integer to a byte array
* @param {Integer} num
* @return {Array} bytes
*/
var intToBytes = function(num) {
var bytes = [];
for(var i=7 ; i>=0 ; --i) {
bytes[i] = num & (255);
num = num >> 8;
}
return bytes;
};
/**
* convert a hex value to a byte array
* @param {String} hex string of hex to convert to a byte array
* @return {Array} bytes
*/
var hexToBytes = function(hex) {
var bytes = [];
for(var c = 0; c < hex.length; c += 2) {
bytes.push(parseInt(hex.substr(c, 2), 16));
}
return bytes;
};

View File

@ -1,8 +1,8 @@
{
"author": "Guy Halford-Thompson <guy@guy.ht> (http://guy.ht)",
"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": "2.0.3",
"version": "2.0.0",
"homepage": "https://github.com/guyht/notp",
"repository": {
"type": "git",
@ -10,14 +10,13 @@
},
"main": "index.js",
"scripts": {
"test": "NODE_ENV=test mocha"
"test": "expresso"
},
"engines": {
"node": "> v0.6.0"
"node": ">= v0.4.10"
},
"dependencies": {},
"devDependencies": {
"mocha": "~1.18.2",
"thirty-two": "0.0.2"
"expresso" : "0.9.0"
}
}

View File

@ -1,98 +0,0 @@
(function (exports) {
'use strict';
exports.sha1Hmac = function (key, bytes) {
if (!window.Unibabel) {
throw new Error("Unibabel.js is required to convert between buffers and binary strings");
}
if ('string' === typeof key) {
throw new Error("use one of Unibabel.utf8ToBuffer(key), Unibabel.base64ToBuffer(key), or Unibabel.hexToBuffer(key) before passing to sha1Hmac(key, bytes)");
}
var Unibabel = window.Unibabel;
function useForge() {
var forge = window.forge;
var hmac = forge.hmac.create();
var digest;
hmac.start('sha1', Unibabel.bufferToBinaryString(key));
hmac.update(Unibabel.bufferToBinaryString(bytes));
digest = hmac.digest().toHex();
return window.Promise.resolve(digest);
}
function useWebCrypto() {
return (window.crypto.subtle||window.crypto.webkitSubtle).importKey(
"raw"
, key
, { name: "HMAC"
, hash: { name: "SHA-1" }
}
, false
, ["sign", "verify"]
)
/*
return crypto.subtle.importKey(
"jwk", //can be "jwk" or "raw"
{ //this is an example jwk key, "raw" would be an ArrayBuffer
kty: "oct",
k: "Y0zt37HgOx-BY7SQjYVmrqhPkO44Ii2Jcb9yydUDPfE",
alg: "HS256",
ext: true,
},
{ //this is the algorithm options
name: "HMAC",
hash: {name: "SHA-256"}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
//length: 256, //optional, if you want your key length to differ from the hash function's block length
},
false, //whether the key is extractable (i.e. can be used in exportKey)
["sign", "verify"] //can be any combination of "sign" and "verify"
)
*/
.then(function (cryptoKey) {
return (window.crypto.subtle||window.crypto.webkitSubtle).sign(
{ name: "HMAC" }
, cryptoKey // from generateKey or importKey above
, new Uint8Array(bytes) // ArrayBuffer of data you want to sign
)
.then(function(signature){
// returns an ArrayBuffer containing the signature
return Unibabel.bufferToHex(new Uint8Array(signature));
});
});
}
if (window.crypto) {
// WebCrypto is so unreliable right now... ugh...
try {
return useWebCrypto().then(function (result) {
return result;
}, function (err) {
console.warn(err);
console.warn(err.stack);
console.warn("WebCrypto failed, trying forge.js");
return useForge();
});
} catch(e) {
console.warn(e);
console.warn(e.stack);
console.warn("WebCrypto threw exception, trying forge.js");
return useForge();
}
}
else if (window.forge) {
return useForge();
}
else {
throw new Error("WebCrypto or forge.js is required to create a sha1 hmac");
}
};
}(
'undefined' !== typeof window ? window : module.exports
, 'undefined' !== typeof process ? process.env.NODE_ENV : false
));

View File

@ -1,15 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>BOTP Test</title>
<meta charset="UTF-8">
</head>
<body>
<script src="bower_components/unibabel/index.js"></script>
<script src="bower_components/unibabel/unibabel.hex.js"></script>
<script src="bower_components/unibabel/unibabel.base32.js"></script>
<script src="sha1-hmac.js"></script>
<script src="index.js"></script>
<script src="test.js"></script>
</body>
</html>

74
test.js
View File

@ -1,74 +0,0 @@
(function (exports) {
'use strict';
var Unibabel = exports.Unibabel;
// Generate a key
function generateOtpKey() {
// 20 cryptographically random binary bytes (160-bit key)
var key = window.crypto.getRandomValues(new Uint8Array(20));
return key;
}
// Text-encode the key as base32 (in the style of Google Authenticator - same as Facebook, Microsoft, etc)
function encodeGoogleAuthKey(bin) {
// 32 ascii characters without trailing '='s
var base32 = Unibabel.bufferToBase32(bin).replace(/=/g, '');
// lowercase with a space every 4 characters
var key = base32.toLowerCase().replace(/(\w{4})/g, "$1 ").trim();
return key;
}
function generateGoogleAuthKey() {
return encodeGoogleAuthKey(generateOtpKey());
}
// Binary-decode the key from base32 (Google Authenticator, FB, M$, etc)
function decodeGoogleAuthKey(key) {
// decode base32 google auth key to binary
var unformatted = key.replace(/\W+/g, '').toUpperCase();
var bin = Unibabel.base32ToBuffer(unformatted);
return bin;
}
// Generate a Google Auth Token
function generateGoogleAuthToken(key) {
var bin = decodeGoogleAuthKey(key);
var totp = exports.totp || require('notp').totp;
return totp.gen(bin);
}
// Verify a Google Auth Token
function verifyGoogleAuthToken(key, token) {
var bin = decodeGoogleAuthKey(key);
var totp = exports.totp || require('notp').totp;
token = token.replace(/\W+/g, '');
// window is +/- 1 period of 30 seconds
return totp.verify(token, bin, { window: 1, time: 30 });
}
exports.generateKey = generateGoogleAuthKey;
exports.generateToken = generateGoogleAuthToken;
exports.verifyToken = verifyGoogleAuthToken;
//var key = exports.generateKey();
var key = 'hxdm vjec jjws rb3h wizr 4ifu gftm xboz';
console.log('key', key);
exports.generateToken(key).then(function (token) {
console.log('token', token);
exports.verifyToken(key, token).then(function (result) {
console.log('verify', result);
});
});
}(
'undefined' !== typeof window ? window : module.exports
));

199
test/notp.js Normal file
View File

@ -0,0 +1,199 @@
var notp = require('..');
/*
* Test HOTtoken. Uses test values from RFcounter 4226
*
*
* The following test data uses the AScounterII string
* "12345678901234567890" for the secret:
*
* Secret = 0x3132333435363738393031323334353637383930
*
* Table 1 details for each count, the intermediate HMAcounter value.
*
* counterount Hexadecimal HMAcounter-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 HOTtoken value.
*
* Truncated
* counterount Hexadecimal Decimal HOTtoken
* 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 key = '12345678901234567890';
var opt = {
window : 0,
};
var HOTP = ['755224', '287082','359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489'];
// counterheck for failure
opt.counter = 0;
assert.ok(!notp.hotp.verify('WILL NOT PASS', key, opt), 'Should not pass');
// counterheck for passes
for(i=0;i<HOTP.length;i++) {
opt.counter = i;
var res = notp.hotp.verify(HOTP[i], key, opt);
assert.ok(res, 'Should pass');
assert.eql(res.delta, 0, 'Should be in sync');
}
};
/*
* Test TOTtoken using test vectors from TOTtoken RFcounter.
*
* see http://tools.ietf.org/id/draft-mraihi-totp-timebased-06.txt
*/
exports.testTOTtoken = function(beforeExit, assert) {
var key = '12345678901234567890';
var opt = {
window : 0,
};
// counterheck for failure
opt.time = 0;
var token = 'windowILLNOTtokenASS';
assert.ok(!notp.totp.verify(token, key, opt), 'Should not pass');
// counterheck for test vector at 59s
opt._t = 59*1000;
var token = '287082';
var res = notp.totp.verify(token, key, opt);
assert.ok(res, 'Should pass');
assert.eql(res.delta, 0, 'Should be in sync');
// counterheck for test vector at 1234567890
opt._t = 1234567890*1000;
var token = '005924';
var res = notp.totp.verify(token, key, opt);
assert.ok(res, 'Should pass');
assert.eql(res.delta, 0, 'Should be in sync');
// counterheck for test vector at 1111111109
opt._t = 1111111109*1000;
var token = '081804';
var res = notp.totp.verify(token, key, opt);
assert.ok(res, 'Should pass');
assert.eql(res.delta, 0, 'Should be in sync');
// counterheck for test vector at 2000000000
opt._t = 2000000000*1000;
var token = '279037';
var res = notp.totp.verify(token, key, opt);
assert.ok(res, 'Should pass');
assert.eql(res.delta, 0, 'Should be in sync');
};
/*
* counterheck for codes that are out of sync
* windowe are going to use a value of counter = 1 and test against
* a code for counter = 9
*/
exports.testHOTPOutOfSync = function(beforeExit, assert) {
var key = '12345678901234567890';
var token = '520489';
var opt = {
counter : 1
};
// counterheck that the test should fail for window < 8
opt.window = 7;
assert.ok(!notp.hotp.verify(token, key, opt), 'Should not pass for value of window < 8');
// counterheck that the test should pass for window >= 9
opt.window = 8;
assert.ok(notp.hotp.verify(token, key, opt), 'Should pass for value of window >= 9');
};
/*
* counterheck for codes that are out of sync
* windowe are going to use a value of T = 1999999909 (91s behind 2000000000)
*/
exports.testTOTPOutOfSync = function(beforeExit, assert) {
var key = '12345678901234567890';
var token = '279037';
var opt = {
_t : 1999999909*1000
};
// counterheck that the test should fail for window < 2
opt.window = 2;
assert.ok(!notp.totp.verify(token, key, opt), 'Should not pass for value of window < 3');
// counterheck that the test should pass for window >= 3
opt.window = 3;
assert.ok(notp.totp.verify(token, key, opt), 'Should pass for value of window >= 3');
};
exports.hotp_gen = function(beforeExit, assert) {
var key = '12345678901234567890';
var opt = {
window : 0,
};
var HOTP = ['755224', '287082','359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489'];
// counterheck for passes
for(i=0;i<HOTP.length;i++) {
opt.counter = i;
assert.eql(notp.hotp.gen(key, opt), HOTP[i], 'HOTP value should be correct');
}
};
exports.totp_gen = function(beforeExit, assert) {
var key = '12345678901234567890';
var opt = {
window : 0,
};
// counterheck for test vector at 59s
opt._t = 59*1000;
assert.eql(notp.totp.gen(key, opt), '287082', 'TOTtoken values should match');
// counterheck for test vector at 1234567890
opt._t = 1234567890*1000;
assert.eql(notp.totp.gen(key, opt), '005924', 'TOTtoken values should match');
// counterheck for test vector at 1111111109
opt._t = 1111111109*1000;
assert.eql(notp.totp.gen(key, opt), '081804', 'TOTtoken values should match');
// counterheck for test vector at 2000000000
opt._t = 2000000000*1000;
assert.eql(notp.totp.gen(key, opt), '279037', 'TOTtoken values should match');
};