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

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

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

  options = options || {};

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

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

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

  return this;
};

module.exports = TOTP;