算法概述
HMAC(Hash-based Message Authentication Code)是一种基于密码学哈希函数的消息认证码算法。它结合了密钥和哈希函数,能够同时验证消息的完整性(未被篡改)和真实性(来自合法发送方)。HMAC-SHA256是目前互联网安全通信中最常用的消息认证方案之一。
HMAC计算流程
HMAC的计算分为以下步骤:
- 密钥填充:将密钥填充或截断为哈希函数的块大小(SHA-256为64字节)
- 生成内部密钥:
ipad = key XOR 0x36 - 生成外部密钥:
opad = key XOR 0x5c - 计算内部哈希:
hash(ipad || message) - 计算最终HMAC:
hash(opad || innerHash)
完整Java实现
import java.nio.charset.StandardCharsets;
/**
* HMAC-SHA256 完整实现
* 基于哈希函数的消息认证码算法
*/
public class HMACSHA256 {
// SHA-256的块大小为64字节(512位)
private static final int BLOCK_SIZE = 64;
// SHA-256输出长度为32字节(256位)
private static final int HASH_LENGTH = 32;
private static final byte IPAD = 0x36;
private static final byte OPAD = 0x5c;
public static byte[] hmac(byte[] key, byte[] message) {
byte[] normalizedKey = normalizeKey(key);
byte[] ipad = new byte[BLOCK_SIZE];
byte[] opad = new byte[BLOCK_SIZE];
for (int i = 0; i < BLOCK_SIZE; i++) {
ipad[i] = (byte) (normalizedKey[i] ^ IPAD);
opad[i] = (byte) (normalizedKey[i] ^ OPAD);
}
byte[] innerData = concat(ipad, message);
byte[] innerHash = sha256(innerData);
byte[] outerData = concat(opad, innerHash);
return sha256(outerData);
}
private static byte[] normalizeKey(byte[] key) {
byte[] result = new byte[BLOCK_SIZE];
if (key.length > BLOCK_SIZE) {
byte[] hashed = sha256(key);
System.arraycopy(hashed, 0, result, 0, hashed.length);
} else {
System.arraycopy(key, 0, result, 0, key.length);
}
return result;
}
private static byte[] concat(byte[] a, byte[] b) {
byte[] result = new byte[a.length + b.length];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}
public static byte[] sha256(byte[] data) {
try {
java.security.MessageDigest digest =
java.security.MessageDigest.getInstance("SHA-256");
return digest.digest(data);
} catch (Exception e) {
throw new RuntimeException("SHA-256 not available", e);
}
}
/**
* 完整手动实现SHA-256(教学用)
*/
public static byte[] sha256Manual(byte[] data) {
int[] h = {
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
};
int[] K = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
byte[] padded = padMessage(data);
for (int chunkStart = 0; chunkStart < padded.length; chunkStart += 64) {
int[] w = new int[64];
for (int i = 0; i < 16; i++) {
w[i] = ((padded[chunkStart + i * 4] & 0xFF) << 24)
| ((padded[chunkStart + i * 4 + 1] & 0xFF) << 16)
| ((padded[chunkStart + i * 4 + 2] & 0xFF) << 8)
| (padded[chunkStart + i * 4 + 3] & 0xFF);
}
for (int i = 16; i < 64; i++) {
int s0 = rightRotate(w[i - 15], 7) ^ rightRotate(w[i - 15], 18) ^ (w[i - 15] >>> 3);
int s1 = rightRotate(w[i - 2], 17) ^ rightRotate(w[i - 2], 19) ^ (w[i - 2] >>> 10);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
int a = h[0], b = h[1], c = h[2], d = h[3];
int e = h[4], f = h[5], g = h[6], hh = h[7];
for (int i = 0; i < 64; i++) {
int S1 = rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25);
int ch = (e & f) ^ ((~e) & g);
int temp1 = hh + S1 + ch + K[i] + w[i];
int S0 = rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22);
int maj = (a & b) ^ (a & c) ^ (b & c);
int temp2 = S0 + maj;
hh = g; g = f; f = e;
e = d + temp1;
d = c; c = b; b = a;
a = temp1 + temp2;
}
h[0] += a; h[1] += b; h[2] += c; h[3] += d;
h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
}
byte[] result = new byte[32];
for (int i = 0; i < 8; i++) {
result[i * 4] = (byte) (h[i] >>> 24);
result[i * 4 + 1] = (byte) (h[i] >>> 16);
result[i * 4 + 2] = (byte) (h[i] >>> 8);
result[i * 4 + 3] = (byte) h[i];
}
return result;
}
private static byte[] padMessage(byte[] data) {
long bitLength = (long) data.length * 8;
int paddingLen = 64 - ((data.length + 9) % 64);
if (paddingLen == 64) paddingLen = 0;
if (paddingLen < 0) paddingLen += 64;
byte[] padded = new byte[data.length + 1 + paddingLen + 8];
System.arraycopy(data, 0, padded, 0, data.length);
padded[data.length] = (byte) 0x80;
for (int i = 0; i < 8; i++) {
padded[padded.length - 1 - i] = (byte) (bitLength >>> (i * 8));
}
return padded;
}
private static int rightRotate(int value, int bits) {
return (value >>> bits) | (value << (32 - bits));
}
public static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
public static void main(String[] args) {
String key = "secret_key_12345";
String message = "Hello, HMAC! This message needs authentication.";
byte[] hmacResult = hmac(key.getBytes(StandardCharsets.UTF_8),
message.getBytes(StandardCharsets.UTF_8));
System.out.println("密钥: " + key);
System.out.println("消息: " + message);
System.out.println("HMAC-SHA256: " + bytesToHex(hmacResult));
String tamperedMessage = message + "x";
byte[] tamperedHmac = hmac(key.getBytes(StandardCharsets.UTF_8),
tamperedMessage.getBytes(StandardCharsets.UTF_8));
System.out.println("\n篡改后消息: " + tamperedMessage);
System.out.println("篡改后HMAC: " + bytesToHex(tamperedHmac));
System.out.println("HMAC是否相同: " + bytesToHex(hmacResult).equals(bytesToHex(tamperedHmac)));
}
}
安全性分析
HMAC的安全性基于以下原则:
– 密钥独立性:不知道密钥时,无法伪造有效的HMAC值
– 抗碰撞性:即使找到哈希碰撞,也难以构造满足HMAC结构的碰撞
– 长度扩展攻击免疫:HMAC的结构天然抵抗单纯哈希函数的长度扩展攻击
应用场景
HMAC广泛应用于API请求签名、JWT令牌验证、TLS/SSL握手、消息队列完整性校验等场景,是现代互联网安全通信的基础设施。