HmacMd5Signature
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
public class HmacMd5Signature {
private static final byte IPAD = 0x36;
private static final byte OPAD = 0x5C;
public static String hmacMd5(String data, String sigSecret) throws Exception {
byte[] keyBytes = sigSecret.getBytes(StandardCharsets.UTF_8);
byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
byte[] paddedKey = Arrays.copyOf(keyBytes, 64);
byte[] xorIpad = new byte[64];
byte[] xorOpad = new byte[64];
for (int i = 0; i < 64; i++) {
xorIpad[i] = (byte) (paddedKey[i] ^ IPAD);
xorOpad[i] = (byte) (paddedKey[i] ^ OPAD);
}
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(xorIpad);
md.update(dataBytes);
byte[] hashIpad = md.digest();
byte[] finalData = new byte[64 + hashIpad.length];
System.arraycopy(xorOpad, 0, finalData, 0, 64);
System.arraycopy(hashIpad, 0, finalData, 64, hashIpad.length);
md.reset();
md.update(finalData);
byte[] hmacMd5 = md.digest();
StringBuilder result = new StringBuilder();
for (byte b : hmacMd5) {
result.append(String.format("%02x", b));
}
return result.toString().toUpperCase();
}
评论 (0)