【发布时间】:2020-10-16 04:00:01
【问题描述】:
在生成 HMAC-SHA1 哈希时遇到问题。我将其转换为 Base64 并将其发送到外部系统,由其验证结果。但是,他们正在生成不同的 Base64 编码哈希。据我所知,他们使用 Java Mac (javax.crypto.mac) 来生成哈希,而我使用的是 Google Guava Codec API。
我检查了几个在线哈希生成器(即https://www.freeformatter.com/hmac-generator.html),它们生成的哈希值与我相同。我尝试了 Apache Commons Codec API,它也产生了相同的结果。然而,这个外部系统正在生成不同的 Base64 编码哈希。密钥/密钥和消息完全相同。
事实证明,首先将哈希转换为字符串而不是字节是问题所在。我首先将哈希转换为字符串,然后使用 Base64 进行编码。外部系统首先将散列转换为字节,然后使用 Base64 进行编码。我发现的在线生成器似乎首先将哈希转换为字符串,就像我一样,这就是我的哈希与在线哈希生成器匹配的原因。
有没有合适的方法来转换哈希?对于良好的实践,我应该使用 asBytes()、toString() 还是其他什么?
这是使用 Guava Codec API 的代码:
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import java.util.Base64;
public class HmacSha1TokenAuth {
public static void main(String[] args) {
String secret = "12345";
String valueToDigest = "TestUser";
byte[] key = secret.getBytes();
Hasher hasher = Hashing.hmacSha1(key).newHasher();
Hasher hasher2 = Hashing.hmacSha1(key).newHasher();
hasher.putBytes(valueToDigest.getBytes());
hasher2.putBytes(valueToDigest.getBytes());
// This is what I used and also found a few online hash generators using the same approach
String hashAsString = hasher.hash().toString();
// This is what the external system used
byte[] hashAsByte = hasher2.hash().asBytes();
String base64AsString = Base64.getEncoder().encodeToString(hashAsString.getBytes());
String base64AsByte = Base64.getEncoder().encodeToString(hashAsByte);
System.out.println("Hash As String: " + hashAsString);
System.out.println("Hash As String(Converted to Bytes): " + hashAsString.getBytes());
System.out.println("Base64 Value of Hash As String: " + base64AsString);
System.out.println("Hash As Byte: " + hashAsByte);
System.out.println("Base64 Value of Hash As Byte: " + base64AsByte);
/*** My Results ***/
// Hash As String: c8094bb1e0896a3f813036bdaeb37b753d9f4f5b
// Hash As String(Converted to Bytes): [B@61443d8f
// Base64 Value of Hash As String: YzgwOTRiYjFlMDg5NmEzZjgxMzAzNmJkYWViMzdiNzUzZDlmNGY1Yg==
/*** External System Results ***/
// Hash As Byte: [B@445b84c0
// Base64 Value of Hash As Byte: yAlLseCJaj+BMDa9rrN7dT2fT1s=
}
}
【问题讨论】:
标签: java hash base64 guava apache-commons