php 网络服务中的校验和实现

Checksum implementation in php web services

我有 php 网络服务来获取 JSON 格式的大量数据。目前我正在使用发送数据和接收数据的计数来比较成功案例。最近我听说了一种叫做校验和的方法。我如何在这种情况下实现校验和?

您可以使用 hash_hmac() 为有效负载签名,使用已知密钥,创建的令牌将使用 HTTP headers 传递。

例如:

<?php
// key which will sign the data 
$key = hash('sha256', 'Unique user data or Some secret');

// your data
$array = [
    'foobar' => 'baz'    
];

// encode the payload
$json = json_encode($array);

// sign it with key
$token = hash_hmac('sha256', $json, $key);

// set response header
header('X-Checksum: '.$token);

echo $json;

这是接收方验证接收到的数据的方式。

// faked: this would be populated by the request/response
$_POST['json'] = $json; 
$_SERVER['X-Checksum'] = $token; 

// verify the data matches token by signing the data with the key
$check = hash_hmac('sha256', $_POST['json'], $key);
if (hash_equals($token, $check)) {
    echo 'Verified';
} else {
    echo 'Tampered';
}

// example tampered data
$_POST['json'] = 'tampered'.$json; 

$check = hash_hmac('sha256', $_POST['json'], $key);
if (hash_equals($token, $check)) {
    echo 'Verified';
} else {
    echo 'Tampered';
}

在线查看:https://3v4l.org/tvUUR