关于php:生成唯一令牌的脚本

Script to generate unique token

我需要生成一个公钥和密钥。

以下代码是否足够?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php

function genToken($salt) {
    $secret = openssl_random_pseudo_bytes(16);

    $apiKey = hash_hmac('sha256', $salt, $secret);
    $apiKey = base64_encode($apiKey);
    $apiKey = str_replace('=', '', $apiKey);

    return $apiKey;
}

$salt='[email protected]';
echo 'pk_' . genToken($salt);
echo"
"
;
echo 'sk_' . genToken($salt);
echo"
"
;


不要把用户的电子邮件当作盐,因为它是可以猜到的。不要自己去做而冒着出错的风险,而是使用一个库。

我建议您使用这个PHP库https://github.com/iricapril/cryptolib(就像本文中建议的那样:生成加密安全令牌)。此库使您能够生成随机字符串,然后通过公开非常实用的方法使用salt对其进行哈希:

此示例(由文档提供,您可以在此处找到:https://cryptolib.ju.je/intro)生成一个salt来散列令牌,您可以将其作为密钥提供给用户:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
// Require the library
require_once('path/to/cryptolib.php');
// Generate a token of 16 char with the library by calling the randomString method.
$token = CryptoLib::randomString(16);
// Generate a salt with the library by calling the generateSalt method
$salt=CryptoLib::generateSalt();
// Hash the token with the salt that was generated
$hash = CryptoLib::hash($token, $salt);

// Salt and hash are then stored in the database.

// $hash and $salt are gotten later from the database, and the token is provided via a POST variable by the user
$isHashCorrect = CryptoLib::validateHash($hash, $_POST['token']);

// If isHashCorrect is true, the user has provided the correct token.
?>

我希望它能帮助你。