如何获取 HMAC_SHA256(x,y) 的前四个字节

How to Get First Four Bytes of HMAC_SHA256(x,y)

我正在实施 ProvablyFair 算法。其中一个步骤是将散列值的前四个字节作为单独的整数。如何提取字节?

这是我尝试过的:

<?php
    
    $ServerSeed = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    
    $ClientSeed ="3333";
    
    $Nonce="10";
    
    $Row_number = "1";
    
    $Data = "{$ClientSeed}:{$Nonce}:{$Row_number}:0";
    
    $Random = hash_hmac('sha256', $ServerSeed , $Data);
    
    $First4Bytes= mb_substr($Random, 0, 4);

如何将 $Random 的前四个字节作为数字 (e.g. [35, 33, 112, 121])

您可以在hash_hmac function to get a raw binary data, unpack it into "bytes" and then use array_slice函数中设置binary选项来获取您需要的字节数:

test.php:

<?php

$data = "Top Secret";
$hash = hash_hmac('sha256', $data, 'secret', true);

printf("%s\n", bin2hex($hash));

$byte_array = array_values(unpack('C*', $hash));

// print_r($byte_array);

print_r(array_slice($byte_array, 0, 4));
print_r(array_slice($byte_array, -4, 4));

测试:

$ php -f test.php
eb409b96bca8118b7e2067b9419d598d928f53251619665743980119de884bfb
Array
(
    [0] => 235
    [1] => 64
    [2] => 155
    [3] => 150
)
Array
(
    [0] => 222
    [1] => 136
    [2] => 75
    [3] => 251
)