在我们的项目中,我们使用以下OpenSSL函数
创建SHA1哈希SHA_CTX ctx;
SHA1_Init (&ctx);
SHA1_Update (&ctx, value, size);
SHA1_Final (returned_hash, &ctx);
我们正在使用密钥,多次调用SHA1_Update。
我必须使用Java验证哈希。我写了以下函数,
public static Mac hmacSha1Init(String key) {
Mac mac = null;
try {
// Get an hmac_sha1 key from the raw key bytes
byte[] keyBytes = key.getBytes();
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
// Get an hmac_sha1 Mac instance and initialize with the signing key
mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
} catch (Exception e) {
throw new RuntimeException(e);
}
return mac;
}
public static Mac hmacSha1Update(String value, Mac mac) {
try {
// update hmac with value
mac.update(value.getBytes());
} catch (Exception e) {
throw new RuntimeException(e);
}
return mac;
}
public static String hmacSha1Final( Mac mac) {
try {
// Compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal();
return Base64.encodeBase64String(rawHmac);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
我正在使用带键的hmacSha1Init并使用Mac多次更新,最后使用mac调用hmacSha1Final。
实施例。
Mac mac = hmacSha1Init("ssdsdsdioj298932276302392pdsdsfsdfs");
mac = hmacSha1Update("value1", mac);
mac = hmacSha1Update("value2", mac);
mac = hmacSha1Update("value3"', mac);
String hash = hmacSha1Final(mac);
但是我没有得到通过OpenSSL生成的相同SHA1哈希。网络上的文档非常有限。有人可以指导我吗
答案 0 :(得分:1)
两个哈希值不同的原因是openssl SHA1算法中使用的输入与Java框架中使用的输入不同。 如果使用MD5算法,您将看到结果相同。在这种情况下,openssl使用相同的。
有什么变化?好吧,openssl认为SHA1不够安全,很好,所以他们决定再转一圈。通常(MD5和Java框架),获取输入字符串并生成它的ASN1 DER编码。然后他们接受它并将其传递给算法。对于SHA1,openssl在生成ASN1 DER编码之前正在进行规范化。它正在计算输入的CANONICAL格式,然后生成ASN1 DER,然后将其传递给算法。
您必须修改Java框架才能获得相同的结果。我也想自己做这件事:))
在这里,您可以在openssl分发列表中找到有关它的帖子:http://openssl.6102.n7.nabble.com/The-new-subject-hash-algorithm-td44844.html
这是ICM Uniwersytet Warszawski的实施。不确定它有多可靠,这就是为什么我要自己尝试。