纠结于在PHP中使用哈希函数生成xml文件的哈希

时间:2018-09-25 14:44:25

标签: java php hash

我正在尝试编写与Java代码等效的PHP:

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
private static final String ALGORITHM = "HmacSHA256";
private static String generateHash(final InputStream is, final int iteration, final String key) throws IOException,
NoSuchAlgorithmException, InvalidKeyException {
Mac sha256_HMAC;
sha256_HMAC = Mac.getInstance(ALGORITHM);
final SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), ALGORITHM);
sha256_HMAC.init(secret_key);
byte[] bytesBuffer = new byte[2048];
int bytesRead = -1;
while ((bytesRead = is.read(bytesBuffer)) != -1) {
sha256_HMAC.update(bytesBuffer, 0, bytesRead);
}
byte[] digestValue = sha256_HMAC.doFinal();
for (int i = 0; i < iteration; i++) {
sha256_HMAC.reset();
digestValue = sha256_HMAC.doFinal(digestValue);
}
final String generatedHash = Base64.encodeBase64String(digestValue);
return generatedHash;
}

到目前为止,我已经生成了以下代码,这些代码未生成预期的输出:

$ihash = hash_init('SHA256',1,$key);
$filehandle  =fopen('path/to/xml/file','r');
while ($buffer=fread($filehandle,"2048")) {
hash_update($inithash, $buffer);
}

$hash = hash_final($inithash);
for($i=0;$i<$iteration;$i++)
{
$inithash=hash_init('SHA256');
$inithash = hash_final($inithash);
}

echo base64_encode($inithash);

但这不会生成预期的输出,我会在询问时共享xml文件。

0 个答案:

没有答案