TOTP Codes From HMAC Counter

Derive HOTP and TOTP one-time codes from HMAC-SHA1 with dynamic truncation, checking the published RFC 4226 and RFC 6238 test vectors end to end.

JavaSecurity Boundaries

Code

snippet
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)");
    }
}

The behavior mapped out

TOTP Codes From HMAC Counter reduces to the class OneTimeCodes.

What to watch for

  • Nothing arrives from a registry; the language ships every API used.

Using it

Output lines are prefixed (counter 0 ->, counter 1 ->, counter 2 ->), so nothing printed loses its link to the step that produced it.

Key statements

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

Interactive Tools for This Topic

FAQ

What does TOTP Codes From HMAC Counter print when run?
Run it as a complete program — the output lines carry labels such as `counter 0 ->`, `counter 1 ->`, `counter 2 ->`.