Skip to content

Instantly share code, notes, and snippets.

@helart
Created August 21, 2020 16:39
Show Gist options
  • Save helart/a3ed983623fe21550f7eda99b0fa2bd8 to your computer and use it in GitHub Desktop.
Save helart/a3ed983623fe21550f7eda99b0fa2bd8 to your computer and use it in GitHub Desktop.
Генерация токенов в PHP
<?php
// Сom_create_guid()
function gen_token()
{
if (function_exists('com_create_guid') === true) {
return trim(com_create_guid(), '{}');
}
return sprintf(
'%04X%04X-%04X-%04X-%04X-%04X%04X%04X',
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(16384, 20479),
mt_rand(32768, 49151),
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 65535)
);
}
echo gen_token(); // 86696D42-B0E9-465E-8374-6475D53FF0DB
// Вариант без com_create_guid:
function gen_token() {
$token = sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff)
);
return $token;
}
echo gen_token(); // a30c8d89-f2aa-4af9-b1df-6b6443349706
// Openssl_random_pseudo_bytes()
function gen_token() {
$bytes = openssl_random_pseudo_bytes(20, $cstrong);
return bin2hex($bytes);
}
echo gen_token(); // a437b15e363ad6cd401a0a87ce0e37171aaeb0c6
// Класс OAuth
$provider = new OAuthProvider();
$token = $provider->generateToken(10);
echo bin2hex($token);
// Random_bytes()
$token = random_bytes(15);
echo bin2hex($token); // ffa7a910ca2dfce501b0d548605aaf
// Функции хеширования
function gen_token() {
$token = md5(microtime() . 'salt' . time());
return $token;
}
echo gen_token(); // 15aada70a60bcbb156459c75d9bea50e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment