← 中文资源

简体中文版本

HMAC 计数器生成一次性口令

用 HMAC-SHA1 加动态截断生成 HOTP/TOTP 一次性口令:计数器打包成 8 字节大端,实现与 RFC 4226、RFC 6238 公布的测试向量逐条对齐。

阅读英文原文

实现说明

活动部件是类 OneTimeCodes。

使用要点

  • 跑完文件,输出里会留下标记——counter 0 ->、counter 1 ->、counter 2 ->。

常见问题

运行「HMAC 计数器生成一次性口令」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 counter 0 ->、counter 1 ->、counter 2 -> 标签标明各步骤。

核心语句

return String.format("%0" + digits + "d", binary % modulus);

代码示例

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class OneTimeCodes {

    // RFC 4226 Appendix D 的参考密钥(ASCII "12345678901234567890")
    private static final byte[] KEY =
            "12345678901234567890".getBytes(StandardCharsets.US_ASCII);

    static String hotp(long counter, int digits) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(KEY, "HmacSHA1"));
        byte[] hash = mac.doFinal(ByteBuffer.allocate(8).putLong(counter).array());

        // 动态截断:末字节低 4 位给出偏移,按大端取 4 字节并屏蔽符号位
        int offset = hash[hash.length - 1] & 0x0F;
        int binary = ((hash[offset] & 0x7F) << 24)
                | ((hash[offset + 1] & 0xFF) << 16)
                | ((hash[offset + 2] & 0xFF) << 8)
                | (hash[offset + 3] & 0xFF);
        int modulus = (int) Math.pow(10, digits);
        return String.format("%0" + digits + "d", binary % modulus);
    }

    public static void main(String[] args) throws Exception {
        // RFC 4226 Appendix D 测试向量
        System.out.println("counter 0 -> " + hotp(0, 6) + " (expect 755224)");
        System.out.println("counter 1 -> " + hotp(1, 6) + " (expect 287082)");
        System.out.println("counter 2 -> " + hotp(2, 6) + " (expect 359152)");

        // TOTP 只是把时间换成 30 秒计数器后复用同一函数;RFC 6238 在 T=59
        // 处的 SHA-1 八位向量正是 hotp(1, 8)
        long now = System.currentTimeMillis() / 1000 / 30;
        System.out.println("totp now  -> " + hotp(now, 6));
        System.out.println("totp T=59 -> " + hotp(59 / 30, 8) + " (expect 94287082)");
    }
}