在我们的项目中,我们使用以下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哈希。web上的文档非常有限。有没有人能告诉我
发布于 2013-10-12 06:45:57
这两种散列不同的原因是openssl SHA1算法中使用的输入与Java框架中使用的输入不同。如果您使用MD5算法,您将看到结果是相同的。在本例中,openssl使用相同的方法。
有什么变化?好吧,openssl认为SHA1不够安全,所以他们决定再给它一次机会。通常(MD5和Java框架),获取输入字符串并生成它的ASN1 DER编码。然后他们把它传递给算法。对于SHA1,openssl在生成ASN1 DER编码之前进行了标准化。它计算输入的规范格式,然后生成ASN1 DER,然后将其传递给算法。
您必须修改Java框架才能获得相同的结果。我自己也在尝试这样做:)
在这里,你可以在openssl分发列表中找到一篇关于它的文章:http://openssl.6102.n7.nabble.com/The-new-subject-hash-algorithm-td44844.html
这里是ICM Uniwersytet Warszawski的实现。不确定它有多可靠,这就是为什么我在尝试自己。
https://stackoverflow.com/questions/17909709
复制相似问题