Php 用于生成唯一令牌的脚本

Php 用于生成唯一令牌的脚本,php,security,token,private-key,public-key,Php,Security,Token,Private Key,Public Key,我需要生成公钥和密钥 下面的代码就足够了吗 <?php function genToken($salt) { $secret = openssl_random_pseudo_bytes(16); $apiKey = hash_hmac('sha256', $salt, $secret); $apiKey = base64_encode($apiKey); $apiKey = str_replace('=', '', $apiKey); retu

我需要生成公钥和密钥

下面的代码就足够了吗

<?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";

不要将用户电子邮件用作盐,因为它可能会被猜测。与其自己使用,否则会有出错的风险,不如使用库

我建议您使用这个PHP库(如本文中建议的:)。此库允许您生成一个随机字符串,然后通过公开非常实用的方法使用salt对其进行哈希:

此示例(由您可以在此处找到的文档提供:)生成salt以散列令牌,您可以将其作为密钥提供给用户:

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


我希望它能帮助您。

为什么使用base64编码?仅用于装饰?是的,用于装饰XD当所有其他操作都失败时,请阅读所有示例此代码的目的是什么?如果非对称加密需要一对加密密钥,那么这个算法是完全错误的。这两个密钥必须在数学上相互关联。我需要实现这一点,所以我需要每个用户唯一的公钥和私钥来生成哈希json