【问题标题】:Libsodium PHP: regular key?Libsodium PHP:常规密钥?
【发布时间】:2019-04-14 15:19:04
【问题描述】:

我正在尝试使用 Libsodium 来加密和解密字符串,但我有一个问题!我目前正在使用两个函数,分别是 safeEncrypt 和 safeDecrypt,代码如下:

<?php
declare(strict_types=1);

/**
 * Encrypt a message
 * 
 * @param string $message - message to encrypt
 * @param string $key - encryption key
 * @return string
 * @throws RangeException
 */
function safeEncrypt(string $message, string $key): string
{
    if (mb_strlen($key, '8bit') !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
        throw new RangeException('Key is not the correct size (must be 32 bytes).');
    }
    $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);

    $cipher = base64_encode(
        $nonce.
        sodium_crypto_secretbox(
            $message,
            $nonce,
            $key
        )
    );
    sodium_memzero($message);
    sodium_memzero($key);
    return $cipher;
}

/**
 * Decrypt a message
 * 
 * @param string $encrypted - message encrypted with safeEncrypt()
 * @param string $key - encryption key
 * @return string
 * @throws Exception
 */
function safeDecrypt(string $encrypted, string $key): string
{   
    $decoded = base64_decode($encrypted);
    $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
    $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

    $plain = sodium_crypto_secretbox_open(
        $ciphertext,
        $nonce,
        $key
    );
    if (!is_string($plain)) {
        throw new Exception('Invalid MAC');
    }
    sodium_memzero($ciphertext);
    sodium_memzero($key);
    return $plain;
}

然后我会像这样使用这些函数:

<?php
// This refers to the previous code block.
require "safeCrypto.php"; 

// Do this once then store it somehow:
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);
$message = 'We are all living in a yellow submarine';

$ciphertext = safeEncrypt($message, $key);
$plaintext = safeDecrypt($ciphertext, $key);

echo "Encrypted: " . $ciphertext;
echo "\r\n";
echo "Decrypted: " . $plaintext;
echo "\r\n";
echo "--------";
echo "\r\n";
echo "KEY: " . $key;

我担心的是密钥不是普通的 ascii,这是我不太明白的其他内容,例如:&amp;w��x�QK��|D���z�����

我能否以某种方式修改函数以使它们生成和使用如下所示的键:S3d3F45g6H7jJ8kG7?我需要这样,以便我可以在 URL 中传递密钥。

感谢您的建议!

【问题讨论】:

    标签: php cryptography libsodium


    【解决方案1】:

    您可以使用sodium_bin2hex($key) 将密钥从二进制编码为十六进制,但不要忘记在使用它进行加密/解密之前使用sodium_hex2bin($key) 对其进行解码。

    为了解决 我需要这样的问题,以便我可以在 URL 中传递密钥。 你的问题的一部分:你不应该这样做。加密密钥必须尽可能安全,通过 URL 传递它们根本不安全。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多