Signature generation and verification of PHP development API interface

In the development process, we often deal with interfaces. Sometimes we call the interfaces of other websites, and sometimes we provide the interfaces of our own websites for others. However, signature verification is indispensable in the process of calling.

When designing signature verification, please pay attention to the following points:

  • Variability: each signature must be different.
  • Timeliness: the timeliness of each request, expiration, invalidation, etc.
  • Uniqueness: each signature is unique.
  • Integrity: it can verify the incoming data and prevent tampering.

1, Method for generating signature parameter sign

Step 1: sort all parameters (note all parameters), except sign itself and the parameters with empty value, in ascending alphabetical order by parameter name.

Step 2: then splice the sorted parameters into a string in the way of parameter 1 value 1 Parameter 2 value 2... Parameter n value n (the parameters and values here must be the original values of the transmission parameters and cannot be processed, such as "convert" and then splice).

Step 3: splice the authentication key key assigned to the access party in front of the string obtained in step 2.

Step 2: add the verification key (the key here is assigned by the interface provider to the interface access party) to the string obtained in the previous step, and then calculate the md5 value to obtain the 32-bit string, and then convert it to uppercase

Step 4: calculate the md5 value (32 bits) of the string in step 3, and then convert it to uppercase. The obtained string is used as the value of sign.

give an example:

Suppose the transmitted data is / interface. PHP? Sign = sign_value & P2 = V2 & P1 = V1 & method = cancel & P3 = & PN = VN (in fact, it is better to send it by post), where the sign_value corresponding to the sign parameter is the value of the signature.

The first step is to splice strings. First remove the sign parameter itself, then remove the parameter p3 with empty value, leaving P2 = V2 & P1 = V1 & method = cancel & amp; PN = VN, and then sort in ascending order according to the parameter name characters, method = cancel & P1 = V1 & P2 = V2 & PN = VN

The second step is to splice the parameter names and values, and finally get the methodcancelp1v1p2v2pnvn The third step is to add the verification key to the string spliced above. We assume abc to get a new string abcmethodcancelp1v1p2v2pnvn

Step 4: md5 calculate the string, assuming that ABCDEF is obtained, and then convert it to uppercase to obtain ABCDEF, which is the sign signature value.

Note: before calculating md5, please ensure that the string encoding of the interface is consistent with that of the access party. For example, utf-8 encoding or GBK encoding is used uniformly. If the encoding methods are inconsistent, the calculated signature will fail to be verified.

2, Signature verification method:

According to the method and rules for generating the signature parameter sign described above, the signature value of the parameter is calculated and compared with the parameter value corresponding to the sign notified in the parameter. If it is consistent, the verification passes. If it is inconsistent, the parameter has been modified.

3, Let's look directly at the code

<?php

// Set a public key and a private key. The public key is used to distinguish users. The private key encrypts data and cannot be made public
$key = "c4ca4238a0b923820dcc509a6f75849b";
$secret = "28c8edde3d61a0411511d3b1866f0636";

// Packets to be sent
$data = array(
    'username' => 'abc@qq.com',
    'sex' => '1',
    'age' => '16',
    'addr' => 'guangzhou',
    'key' => $key,
    'timestamp' => time(),
);

// Get sign
function getSign($secret, $data) {
    // Sort the values of the array by key
    ksort($data);
    // Form of generated url
    $params = http_build_query($data);
    // Generate sign
    $sign = md5($params . $secret);
    return $sign;
}

// Send data plus sign
$data['sign'] = getSign($secret, $data);

/**
 * Verify whether the sign is legal in the background
 * @param  [type] $secret [description]
 * @param  [type] $data   [description]
 * @return [type]         [description]
 */
function verifySign($secret, $data) {
    // Verify that there is a signature in the parameter
    if (!isset($data['sign']) || !$data['sign']) {
        echo 'The sent data signature does not exist';
        die();
    }
    if (!isset($data['timestamp']) || !$data['timestamp']) {
        echo 'The data parameter sent is illegal';
        die();
    }
    // Validation request, 10 minute failure
    if (time() - $data['timestamp'] > 600) {
        echo 'Validation failed, please resend the request';
        die();
    }
    $sign = $data['sign'];
    unset($data['sign']);
    ksort($data);
    $params = http_build_query($data);
    // $secret is obtained by querying the api database through the key
    $sign2 = md5($params . $secret);
    if ($sign == $sign2) {
        die('Verification passed');
    } else {
        die('Illegal request');
    }
}
?>
Copy code

Added by johnbrayn on Thu, 09 Dec 2021 08:30:18 +0200