我正在尝试使用 HMAC SHA1 单向算法
这是我的代码
@Test
public void encodeTest() {
String HMAC_SHA1_ALGORITHM = "HmacSHA1";
String EXPECTED_BASE_64 = "g9OrJ8pQNYprnXuBPFXcirrqpxE=";
String text = "encodeme";
String result;
try {
SecretKeySpec signingKey = new SecretKeySpec(
"MSbN2crsrdTEsLetTixpV46q+fTZotdZjwoEpO62vYk=".getBytes(),
HMAC_SHA1_ALGORITHM);
// Get an hmac_sha1 Mac instance and initialise with the signing key
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
// Compute the hmac
byte[] rawHmac = mac.doFinal(text.getBytes());
// Convert raw bytes to Hex
byte[] hexBytes = new Hex().encode(rawHmac);
// Covert array of Hex bytes to a String
result = new String(hexBytes, "ISO-8859-1");
// Ok, this matches with the web
System.out.println("HEX:" + result);
String encodedBase64 = new String(Base64.encodeBase64(hexBytes));
System.out.println("BASE64:" + encodedBase64);
// In the web i get a smaller chain, why?
System.out.println("EXPECTED BASE64:" + EXPECTED_BASE_64);
Assert.assertEquals(EXPECTED_BASE_64, encodedBase64);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
输出是
十六进制:83d3ab27ca50358a6b9d7b813c55dc8abaeaa711 BASE64:ODNkM2FiMjdjYTUwMzU4YTZiOWQ3YjgxM2M1NWRjOGFiYWVhYTcxMQ==
预期 BASE64:g9OrJ8pQNYprnXuBPFXcirrqpxE=
我使用这些在线网站定义了我的期望
http://hash.online-convert.com/sha1-generator
文本=编码
使用共享密钥
键=MSbN2crsrdTEsLetTixpV46q+fTZotdZjwoEpO62vYk=
我得到的结果略有不同
十六进制:83d3ab27ca50358a6b9d7b813c55dc8abaeaa711 十六进制:83D3AB27CA50358A6B9D7B813C55DC8ABAEAA711 h:e:x: 83:d3:ab:27:ca:50:35:8a:6b:9d:7b:81:3c:575:dca:a:a:8 11 base64: g9OrJ8pQNYprnXuBPFXcirrqpxE=
如您所见,十六进制输出匹配 100%,但是 base64 输出根本不匹配
为了验证问题不在那个站点,我去了另一个站点,只是为了使用 base64 对十六进制字符串进行编码,然后我又得到了相同的结果......
http://tomeko.net/online_tools/hex_to_base64.php?lang=en
任何人都知道为什么会这样?
提前致谢!