totp.js 1017 Bytes
/**
 * Created by lintry on 2017/5/19.
 */

const _ = require('lodash'),
    crypto_utils = require('kml-crypto-utils'),
    speakeasy = require('speakeasy'),
    Authenticator = require('./authenticator');

/**
 * 生成密钥并加密
 * @return {*}
 */
const createSecret = function () {
    return crypto_utils.AESEncode(speakeasy.generateSecret({length: 20}).base32);
};

const TOTP = function (options) {
    if (!(this instanceof TOTP)) {
        return new TOTP(options)
    }


    options = options || {};

    const TOTP_OPTIONS = {
        encoding: options.encoding || 'base32',
        step: options.step || 30,
        algorithm: options.algorithm || 'sha512'
    };

    /**
     * 解析密钥
     * @param secret
     * @return {Authenticator}
     */
    this.parse = function (secret) {
        return new Authenticator(crypto_utils.AESDecode(secret), TOTP_OPTIONS)
    };

    return this;
};

TOTP.createSecret = createSecret;
TOTP.prototype.createSecret = createSecret;

module.exports = TOTP;