【问题标题】:Script to generate unique token生成唯一令牌的脚本
【发布时间】:2016-03-15 23:20:26
【问题描述】:

我需要生成公钥和私钥。

下面的代码就够了吗?

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

【问题讨论】:

  • 为什么使用base64编码?只是为了装饰?
  • 是的装饰 XD
  • 当一切都失败时Try using the manual阅读所有示例
  • 这段代码的目的是什么?如果您需要一对用于非对称加密的加密密钥,那么这个算法是完全错误的。两个键之间必须在数学上相互关联。
  • 我需要实现这个websec.io/2013/02/14/…,所以我需要每个用户唯一的公钥和生成哈希json的私钥

标签: php security token private-key public-key


【解决方案1】:

不要将用户电子邮件用作盐,因为它可能会被猜到。与其自己做会有错误的风险,不如改用库。

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

此示例(由您可以在此处找到的文档提供: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.
?>

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2016-01-24
    • 2014-04-16
    • 2015-01-02
    • 1970-01-01
    • 2017-04-15
    • 2019-06-04
    • 1970-01-01
    • 2016-12-17
    • 2013-01-16
    相关资源
    最近更新 更多