Generates the OTP code

@module otplib-core/totpToken
@param {string} secret - your secret that is used to generate the token
@param {object} options - allowed options as specified in totpOptions()
@return {string} OTP Code
769906
function totpToken(secret, options) {
  if (typeof options.epoch !== 'number') {
    throw new Error('Expecting options.epoch to be a number');
  }

  if (typeof options.step !== 'number') {
    throw new Error('Expecting options.step to be a number');
  }

  const counter = totpCounter(options.epoch, options.step);
  return hotpToken(secret, counter, options);
}
417508
public static Token parseToken(byte[] secret, String token) {
        Token tk = new Token();
        if (S.blank(token)) return tk;
        String s = "";
        try {
            s = Crypto.decryptAES(token, secret);
        } catch (Exception e) {
            return tk;
        }
        String[] sa = s.split("\\|");
        if (sa.length < 2) return tk;
        tk.id = sa[0];
        try {
            tk.due = Long.parseLong(sa[1]);
            if (tk.expired()) {
                return tk;
            }
        } catch (Exception e) {
            tk.due = $.ms() - 1000 * 60 * 60 * 24;
            return tk;
        }
        if (sa.length > 2) {
            sa = Arrays.copyOfRange(sa, 2, sa.length);
            tk.payload.addAll(C.listOf(sa));
        }
        return tk;
    }
1305476
function HTTPOptions(options) {
  if (!(this instanceof HTTPOptions))
    return new HTTPOptions(options);

  this.network = Network.primary;
  this.logger = null;
  this.node = null;
  this.apiKey = base58.encode(random.randomBytes(20));
  this.apiHash = digest.hash256(Buffer.from(this.apiKey, 'ascii'));
  this.noAuth = false;

  this.prefix = null;
  this.host = '127.0.0.1';
  this.port = 8080;
  this.ssl = false;
  this.keyFile = null;
  this.certFile = null;

  this.fromOptions(options);
}
925551
function createWallet (password, options) {
  if (!password || password.length > 255) {
    return Promise.reject('Password must exist and be shorter than 256 characters')
  }

  options = options || {}
  var email = options.email
  var firstLabel = options.firstLabel
  var privateKey = options.privateKey
  var secPass = options.secondPassword
  var isHdWallet = Boolean(options.hd)

  Blockchain.API.API_CODE = options.api_code

  // Handle response from WalletNetwork
  var generatedUUIDs = function (uuids) {
    var guid = uuids[0]
    var sharedKey = uuids[1]

    if (!guid || !sharedKey || guid.length !== 36 || sharedKey.length !== 36) {
      throw 'Error generating wallet identifier'
    }

    return { guid: guid, sharedKey: sharedKey }
  }

  // Generate new Wallet JSON, add first key
  var newWallet = function (uuids) {
    var walletJSON = {
      guid: uuids.guid,
      sharedKey: uuids.sharedKey,
      double_encryption: false,
      options: {
        pbkdf2_iterations: 5000,
        html5_notifications: false,
        fee_per_kb: 10000,
        logout_time: 600000
      }
    }

    var createHdWallet = function (label) {
      label = label == null ? 'My Bitcoin Wallet' : label
      var mnemonic = BIP39.generateMnemonic(undefined, Blockchain.RNG.run.bind(Blockchain.RNG))
      var hd = HDWallet.new(mnemonic)
      hd.newAccount(label)
      return hd
    }

    var createLegacyAddress = function (priv, label) {
      return priv ? Address.import(priv, label) : Address.new(label)
    }

    if (isHdWallet) {
      var hdJSON = createHdWallet(firstLabel).toJSON()
      hdJSON.accounts = hdJSON.accounts.map(function (a) { return a.toJSON() })
      walletJSON.hd_wallets = [hdJSON]
    } else {
      winston.warn(warnings.CREATED_NON_HD)
      var firstAddress = createLegacyAddress(privateKey, firstLabel)
      walletJSON.keys = [firstAddress.toJSON()]
    }

    if (typeof secPass === 'string' && secPass.length) {
      walletJSON = JSON.parse(JSON.stringify(new Wallet(walletJSON).encrypt(secPass)))
    }

    return walletJSON
  }

  // Encrypt and push new wallet to server
  var insertWallet = function (wallet) {
    var data = JSON.stringify(wallet, null, 2)
    var enc = Blockchain.WalletCrypto.encryptWallet(data, password, wallet.options.pbkdf2_iterations, 2.0)
    var check = sha256(enc).toString('hex')

    // Throws if there is an encryption error
    Blockchain.WalletCrypto.decryptWallet(enc, password, function () {}, function () {
      throw 'Failed to confirm successful encryption when generating new wallet'
    })

    var postData = {
      guid: wallet.guid,
      sharedKey: wallet.sharedKey,
      length: enc.length,
      payload: enc,
      checksum: check,
      method: 'insert',
      format: 'plain'
    }

    if (email) postData.email = email

    return Blockchain.API.securePost('wallet', postData).then(function () {
      if (isHdWallet) {
        var account = wallet.hd_wallets[0].accounts[0]
        return { guid: wallet.guid, address: account.xpub, label: account.label }
      } else {
        var firstKey = wallet.keys[0]
        return { guid: wallet.guid, address: firstKey.addr, label: firstKey.label, warning: warnings.CREATED_NON_HD }
      }
    })
  }

  return WalletNetwork.generateUUIDs(2)
    .then(generatedUUIDs)
    .then(newWallet)
    .then(insertWallet)
    .catch(function (err) { throw err === 'Unknown API Key' ? 'ERR_API_KEY' : err })
}
1039848
public static Token token(String appid,String secret){
		HttpUriRequest httpUriRequest = RequestBuilder.get()
				.setUri(BASE_URI + "/cgi-bin/token")
				.addParameter("grant_type","client_credential")
				.addParameter("appid", appid)
				.addParameter("secret", secret)
				.build();
		return LocalHttpClient.executeJsonResult(httpUriRequest,Token.class);
	}
919912
function generatePKP (privateKey, dicPopl, idProvoz, idPokl, poradCis, datTrzby, celkTrzba) {
  const options = [dicPopl, idProvoz, idPokl, poradCis, datTrzby, celkTrzba]
  const strToHash = options.join('|')
  const sign = crypto.createSign('RSA-SHA256')
  sign.write(strToHash)
  sign.end()
  return sign.sign(privateKey, 'base64')
}
589499
function(secret) {
        var keyIv;
        if (!secret) {
          throw new CError('missing secret').log();
        }
        // secret is a Base64 string
        if(secret.isBase64()){
          try {
            keyIv = forge.util.decode64(secret);
          } catch (e) {
            throw new CError('secret not valid').log();
          }
        } else {
          keyIv = secret;
        }
        return keyIv;
      }
25530
function() {
      var secret;
      if (!this.getSecret()) {
        throw new CError('missing secret').log();
      }
      try {
        secret = this.encoder.encryptRsa(this.getSecret());
      } catch (e) {
        throw new CError({
          body: {
            code: 'ImATeapot',
            message: 'unable to encrypt secret',
            cause: e
          }
        }).log('body');
      }
      if (this.getMode() !== mode1 && this.getMode() !== mode2) {
        throw new CError('unexpected mode').log();
      }
      if (!this.getSid()) {
        throw new CError('missing sid').log();
      }
      return {
        mode: this.getMode(),
        secret: secret,
        sid: this.getSid()
      };
    }
661211
function tokenCredentials (authorization, secret, done) {
  var strategy = this
  var provider = strategy.provider
  var endpoint = strategy.endpoints.token
  var client = strategy.client
  var method = endpoint.method && endpoint.method.toLowerCase()
  var url = endpoint.url
  var header = endpoint.header || 'Authorization'
  var scheme = endpoint.scheme || 'OAuth'
  var accept = endpoint.accept || 'application/x-www-form-urlencoded'
  var key = client.oauth_consumer_key
  var signer = provider.oauth_signature_method || 'PLAINTEXT'
  var verifier = authorization.oauth_verifier || null
  var token = authorization.oauth_token
  var params = {}

  // Initialize request
  var req = request[method || 'post'](url)

  // Build request parameters
  params.oauth_consumer_key = key
  params.oauth_signature_method = signer
  params.oauth_timestamp = timestamp()
  params.oauth_nonce = nonce(32)
  params.oauth_token = token
  params.oauth_verifier = verifier
  params.oauth_version = '1.0'

  var input = signatureBaseString(method, url, normalizeParameters(params))
  params.oauth_signature = sign(signer, input, secret)

  // Set Authorization header
  req.set(header, scheme + ' ' + authorizationHeaderParams(params))

  // Set other headers
  req.set('Accept', accept)
  req.set('User-Agent', agent)

  // Execute request
  return req.end(function (err, res) {
    if (err) { return done(err) }
    var response = qs.parse(res.text)

    if (res.statusCode !== 200) {
      return done(new Error("Couldn't obtain token credentials"))
    }

    done(null, response)
  })
}
106254
function cookiee(secret, opt) {

  if (!secret) {
    throw new TypeError('secret required');
  }
  var options = opt || Object.create(null);
  var my = {
    secret: Buffer.isBuffer(secret) ? secret : new Buffer(secret),
    cipher: String(options.cipher || 'arc4'),
    cookie: String(options.cookie || 'vault'),
    domain: String(options.domain || ''),
    path: String(options.path || '/'),
    maxAge: Number(options.maxAge) || 1000 * 3600 * 24 * 365,
    httpOnly: Boolean(options.httpOnly),
    secure: Boolean(options.secure),
    signed: Boolean(options.signed),
    encoding: String(options.encoding || 'hex'),
    extra: Array.isArray(options.extra) === true ? options.extra : []
  };

  return Boolean(options.signed) ? new Signed(my) : new Normal(my);
}
1096257
function BlockTemplate(options) {
  if (!(this instanceof BlockTemplate))
    return new BlockTemplate(options);

  this.prevBlock = encoding.NULL_HASH;
  this.version = 1;
  this.height = 0;
  this.time = 0;
  this.bits = 0;
  this.target = encoding.ZERO_HASH;
  this.locktime = 0;
  this.mtp = 0;
  this.flags = 0;
  this.coinbaseFlags = DUMMY;
  this.witness = false;
  this.address = new Address();
  this.reserve = new Address();
  this.sigops = 400;
  this.weight = 4000;
  this.interval = 210000;
  this.fees = 0;
  this.tree = new MerkleTree();
  this.commitment = encoding.ZERO_HASH;
  this.left = DUMMY;
  this.right = DUMMY;
  this.items = [];

  if (options)
    this.fromOptions(options);
}
648505
func GenerateCodeCustom(secret string, counter uint64, opts ValidateOpts) (passcode string, err error) {
	// As noted in issue #10 and #17 this adds support for TOTP secrets that are
	// missing their padding.
	secret = strings.TrimSpace(secret)
	if n := len(secret) % 8; n != 0 {
		secret = secret + strings.Repeat("=", 8-n)
	}

	// As noted in issue #24 Google has started producing base32 in lower case,
	// but the StdEncoding (and the RFC), expect a dictionary of only upper case letters.
	secret = strings.ToUpper(secret)

	secretBytes, err := base32.StdEncoding.DecodeString(secret)
	if err != nil {
		return "", otp.ErrValidateSecretInvalidBase32
	}

	buf := make([]byte, 8)
	mac := hmac.New(opts.Algorithm.Hash, secretBytes)
	binary.BigEndian.PutUint64(buf, counter)
	if debug {
		fmt.Printf("counter=%v\n", counter)
		fmt.Printf("buf=%v\n", buf)
	}

	mac.Write(buf)
	sum := mac.Sum(nil)

	// "Dynamic truncation" in RFC 4226
	// http://tools.ietf.org/html/rfc4226#section-5.4
	offset := sum[len(sum)-1] & 0xf
	value := int64(((int(sum[offset]) & 0x7f) << 24) |
		((int(sum[offset+1] & 0xff)) << 16) |
		((int(sum[offset+2] & 0xff)) << 8) |
		(int(sum[offset+3]) & 0xff))

	l := opts.Digits.Length()
	mod := int32(value % int64(math.Pow10(l)))

	if debug {
		fmt.Printf("offset=%v\n", offset)
		fmt.Printf("value=%v\n", value)
		fmt.Printf("mod'ed=%v\n", mod)
	}

	return opts.Digits.Format(mod), nil
}
362594
public static <T> String generateSign(RestRequestParam<T> param, String secretkey) {
    TreeMap<String, String> paramsMap = new TreeMap<String, String>();
    paramsMap.put("accesskey", param.getCommon().getAccesskey());
    paramsMap.put("timestamp", Long.toString(param.getCommon().getTimestamp()));

    //    for (Map.Entry<String, String> entry : param.getData())
    //    {
    //        paramsMap.put(entry.getKey(), entry.getValue().toString());
    //    }
    paramsMap.put("secretkey", secretkey);
    return generateSignByRule(paramsMap);
  }
181636
function (options, callback) {

        LOG.debug('preauth#createPreauth called');
        LOG.debug('Validating options');

        try {

            options = new preauthOptions.CreatePreauth().validate(options);

        } catch (err) {

            if (err.name === 'InvalidOption') {

                LOG.error('Invalid options specified: %s', err.message);

                callback(
                    commonErrors.InvalidOption(
                        undefined,
                        {
                            message: err.message
                        }
                    )
                );

            } else {

                LOG.error('System error: %s', err.message);

                callback(
                    commonErrors.SystemError(
                        undefined,
                        {
                            message: err.message
                        }
                    )
                );

            }

            return;

        }

        var timestamp = options.timestamp;

        if (!timestamp) {

            timestamp = new Date().getTime();

        }

        LOG.debug('Generating preauth key');

        var pakCreator = crypto.createHmac('sha1', options.key)
            .setEncoding('hex');

        pakCreator.write(
            util.format(
                '%s|%s|%s|%s',
                options.byValue,
                options.by,
                options.expires,
                timestamp
            )
        );
        pakCreator.end();
        var pak = pakCreator.read();

        LOG.debug('Returning preauth key %s', pak);

        callback(null, pak);

    }
733686
def generate_hotp(secret, counter=4):
    
    # https://tools.ietf.org/html/rfc4226
    msg = struct.pack('>Q', counter)
    digest = hmac.new(to_bytes(secret), msg, hashlib.sha1).digest()

    ob = digest[19]
    if PY2:
        ob = ord(ob)

    pos = ob & 15
    base = struct.unpack('>I', digest[pos:pos + 4])[0] & 0x7fffffff
    token = base % 1000000
    return token
607768
function authenticate(options) {
        options = options || {};

        var authenticators = [
            passport.authenticate(['copress-oauth2-bearer', 'copress-oauth2-mac'],
                options)];
        if (options.scopes || options.scope) {
            authenticators.push(scopeValidator(options));
        }
        authenticators.push(oauth2Provider.errorHandler());
        return authenticators;
    }
1210437
function TChannelHTTP(options) {
    if (!(this instanceof TChannelHTTP)) {
        return new TChannelHTTP(options);
    }
    var self = this;
    if (options) {
        self.lbpool = options.lbpool;
    }
}