用于生成唯一令牌的脚本


Script to generate unique token

我需要生成公钥和密钥。

以下代码就足够了吗?

<?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 = 'UsernameEmail@gmail.com';
echo 'pk_' . genToken($salt);
echo "'n";
echo 'sk_' . genToken($salt);
echo "'n";

不要将用户电子邮件用作盐,因为它可以被猜到。与其冒着出错的风险自己做,不如使用库。

我建议你 https://github.com/IcyApril/CryptoLib 使用这个PHP库(就像这篇文章中提出的:生成加密安全的令牌)。这个库使您能够生成一个随机字符串,然后通过公开非常实用的方法使用盐对其进行哈希处理:

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

<?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.
?>

我希望它能帮助你。