【问题标题】:Generate a key in PHP for AES 256在 PHP 中为 AES 256 生成密钥
【发布时间】:2013-06-24 16:05:43
【问题描述】:

如何使用 PHP 安全地生成适合使用 AES 256 散列数据的密钥?

我试过谷歌搜索,发现很多关于如何使用 PHP 使用 AES 256 加密数据的信息,但是所有这些示例都使用现有的预生成密钥,而我需要在 PHP 中生成密钥。

【问题讨论】:

  • 你尝试用谷歌搜索你的问题吗?你有没有想出什么有用的东西?是否需要“在 php”中生成密钥,或者简单地提供给您。大概您不会重复生成新密钥 - 还是会?
  • 密钥必须在php中生成。我没有发现任何真正有用的东西。
  • 我试图用谷歌搜索这个问题并找到了这个!

标签: php key aes


【解决方案1】:

openssl-pkey-new() 函数正是您正在寻找的。

至于IV,可以看How to securely generate an IV for AES CBC Encryption? 推荐使用openssl-random-pseudo-bytes

但是,如果您真的在寻找一个有用的页面,谷歌“在 PHP 中实现 AES” - 作为第一个点击,您会找到 http://www.movable-type.co.uk/scripts/aes-php.html,它肯定会教给您您需要知道的一切...

【讨论】:

  • Erm,生成一个 PK 密钥对,而不是一个 aes 密钥?除非我误解了。
【解决方案2】:

从 php7 开始,您可以使用 random_bytes() 函数来生成加密安全的伪随机字节。

该函数使用的随机性来源如下:

  • 在 Windows 上,» CryptGenRandom() 将始终被使用。
  • 在 Linux 上,如果可用,将使用 » getrandom(2) 系统调用。
  • 在其他平台上,将使用 /dev/urandom。
  • 如果上述来源均不可用,则 会抛出异常

查看php manual了解更多信息

【讨论】:

  • 正在研究 openssl-random-pseudo-bytes() 与 random_bytes(),我发现了这个 reddit post
【解决方案3】:

如果你不想依赖库,你可以在 Linux/Unix 机器上使用这个函数。等同于openssl-random-pseudo-bytes:

<?php
$key_size = 256;  //For a 256 bit key, you can use 128 or 512 as well. 
$key = uuid_gen(($key_size / 8)); //8 bits in a byte

echo 'key length is ' .strlen($key) ."\n"; //The number of bytes

/* Returns Raw Binary */
function uuid_gen($length) {

    $fp = @fopen('/dev/urandom','rb');

    if ($fp !== FALSE) {
        $result .= @fread($fp, $length);
        @fclose($fp);
    } else {
        trigger_error('Can not open /dev/urandom.');
    }

    return $result;
}

【讨论】:

    猜你喜欢
    • 2013-06-16
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    相关资源
    最近更新 更多