首页 > 解决方案 > 为什么在这个 TOTP 函数中有时会得到 5 位而不是 6 位?

问题描述

我在我的 Node 应用程序中使用来自https://hackernoon.com/how-to-implement-google-authenticator-two-factor-auth-in-javascript-091wy3vh3的代码,它生成基于时间的 OTP 6 位代码。

它工作正常,但是,它时不时地只返回一个 5 位数的代码而不是 6 位数。

function generateHOTP(secret, counter) {
    const decodedSecret = base32.decode.asBytes(secret);
    const buffer = Buffer.alloc(8);
    for (let i = 0; i < 8; i++) {
        buffer[7 - i] = counter & 0xff;
        counter = counter >> 8;
    }

    // Step 1: Generate an HMAC-SHA-1 value
    const hmac = crypto.createHmac('sha1', Buffer.from(decodedSecret));
    hmac.update(buffer);
    const hmacResult = hmac.digest();

    // Step 2: Generate a 4-byte string (Dynamic Truncation)
    const code = dynamicTruncationFn(hmacResult);

    // Step 3: Compute an HOTP value
    return code % 10**6;
    //return code;
}

标签: javascriptnode.jsone-time-passwordtwo-factor-authentication

解决方案


推荐阅读