这是创建键控哈希摘要的函数的Java代码,我想在PHP代码中执行相同操作。
Java代码:
private 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);
}
return Base64.encodeBase64String(digestValue);
}
这是我试过的PHP代码,但两个代码的输出都不一样。
而且我认为我在某处遗漏了一些东西,因为我不知道PHP中每个Java代码语句的替代方法:
function generateHash($file, $iteration, $key){
//$hash = hash_hmac('sha256', 'hello, world!', 'mykey');
$inithash=hash_init('SHA256',1,$key);
//mb_strlen($string, '8bit')
while ($buffer=fread($file,"2048")) {
hash_update($inithash, $buffer);
}
$hash = hash_final($inithash);
$hashbyte = unpack('C*',$hash);
for($i=0;$i<$iteration;$i++)
{
//unset($hashbyte);
$inithash=hash_init('SHA256');
$inithash = hash_final($inithash);
}
return base64_encode($inithash);
}