简体   繁体   中英

Script to generate unique token

I need generate a public key and secret key.

Is the following code would be enough?

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

Do not use as salt the user email because it can be guessed.Instead of doing it yourself with a risk of error use a library instead.

I suggest you to use this PHP library https://github.com/IcyApril/CryptoLib (like proposed in this post : Generating cryptographically secure tokens ). This library enables you to generate a random string then to hash it using a salt by exposing very practical methods :

This example (provided by the documentation that you can find here : https://cryptolib.ju.je/#intro ) generate a salt to hash a token, that you can provide to your user as a key :

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

I hope it will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM