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.
Code
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
TOTP URI Builder & Code GeneratorBuild valid otpauth://totp QR provisioning URIs and compute RFC 6238 HMAC-SHA1, SHA-256, or SHA-512 verification codes locally using Web Crypto.HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.
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 ->`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.