Skip to content

Commit

Permalink
feat: cryptojs sample
Browse files Browse the repository at this point in the history
  • Loading branch information
yeojz committed Feb 13, 2019
1 parent 5382b6b commit 0d13c10
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 0 deletions.
6 changes: 6 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Expand Up @@ -49,6 +49,7 @@
"babel-plugin-module-resolver": "^3.1.0",
"coveralls": "^3.0.0",
"create-hmac": "^1.1.4",
"crypto-js": "^3.1.9-1",
"dtslint": "^0.3.0",
"eslint": "^5.0.0",
"eslint-config-prettier": "^3.0.0",
Expand Down
48 changes: 48 additions & 0 deletions packages/otplib-cryptojs/crypto.js
@@ -0,0 +1,48 @@
import CryptoJS from 'crypto-js';

/**
* Crypto replacement using crypto-js
*
* @module otplib-cryptojs/crypto
*/
class CryptoExpo {
constructor(algorithm, secret) {
this.algorithm = algorithm.toLowerCase();
this.secret = secret.toString('ascii');
}

static createHmac(algorithm, hmacSecret) {
return new CryptoExpo(algorithm, hmacSecret);
}

update(bufferHex) {
this.hex = bufferHex.toString('hex');
return this;
}

getEncoder() {
switch (this.algorithm) {
case 'sha1':
return CryptoJS.HmacSHA1;
case 'sha256':
return CryptoJS.HmacSHA256;
case 'sha512':
return CryptoJS.HmacSHA512;
default:
throw new Error(
`Unsupported algorithm ${
this.algorithm
}. Accepts: sha1, sha256, sha512`
);
}
}

digest() {
const encoder = this.getEncoder();
const message = CryptoJS.enc.Hex.parse(this.hex);
const strDigest = String(encoder(message, this.secret));
return Buffer.from(strDigest, 'hex');
}
}

export default CryptoExpo;
26 changes: 26 additions & 0 deletions packages/otplib-cryptojs/index.js
@@ -0,0 +1,26 @@
import hotp from 'otplib-hotp';
import totp from 'otplib-totp';
import authenticator from 'otplib-authenticator';
import crypto from './crypto';

/**
* otplib
*
* One-Time Password Library
*
* ```js
* {
* authenticator // instance
* hotp // instance
* totp // instance
* }
* ```
*
* @module otplib
* @since 3.0.0
*/
authenticator.defaultOptions = { crypto };
hotp.defaultOptions = { crypto };
totp.defaultOptions = { crypto };

export { authenticator, hotp, totp };
17 changes: 17 additions & 0 deletions packages/otplib-cryptojs/index.spec.js
@@ -0,0 +1,17 @@
import * as otplib from './index';
import rfc6238 from 'tests/rfc6238';

describe('index', () => {
rfc6238.table.forEach(row => {
const id = `${row.algorithm} / ${row.epoch}`;
test(`[${id}] otplib.totp`, () => {
otplib.totp.options = {
epoch: row.epoch,
algorithm: row.algorithm,
digits: 8
};

expect(otplib.totp.check(row.token, rfc6238.secret)).toBe(true);
});
});
});

0 comments on commit 0d13c10

Please sign in to comment.