首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Libsodium :普通密钥?

Libsodium :普通密钥?
EN

Stack Overflow用户
提问于 2019-04-14 23:19:04
回答 1查看 401关注 0票数 0

我正在尝试使用trying来加密和解密字符串,但我有一个问题!我目前使用了两个名为safeEncrypt和safeDecrypt的函数,代码如下:

代码语言:javascript
复制
<?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;
}

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

代码语言:javascript
复制
<?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中,而是其他我不太理解的东西,比如:&w��x�QK��|D���z�����

我能不能通过某种方式修改这些函数,让它们生成并使用类似如下的键:S3d3F45g6H7jJ8kG7?我需要这样做,这样我才能在URL中传递密钥。

谢谢你的建议!

EN

回答 1

Stack Overflow用户

发布于 2019-09-07 17:14:29

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55676862

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档