【问题标题】:PHP Sodium Decryption Returns FalsePHP 钠解密返回 False
【发布时间】:2021-03-08 02:18:26
【问题描述】:

我是 php 和 stackoverflow 的新手,因此可能会发生一些错误。如果有请告诉我,我会尽快解决。

我的加密功能:

function encrypt($data){
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = sodium_crypto_secretbox($data, $nonce, $GLOBALS['key']);
$ciphertext = base64_encode($ciphertext);
$ciphertext .= "[-SPLIT-]" . base64_encode($nonce);

return $ciphertext;}

我的解密函数:

function decrypt($data){   
$data = explode("[-SPLIT-]", $data);
$ciphertext = base64_decode($data[0]);
$nonce = base64_decode($data[1]);
$plaintext = sodium_crypto_secretbox_open($ciphertext, $nonce, $GLOBALS['key']);

if(!$plaintext){$plaintext = "FAILED";}
return $plaintext;}

我已经做了足够多的测试,知道我正在将从加密函数返回的 $ciphertext 传递给解密函数。

如何使函数返回在我的加密函数中加密的解密字符串?

【问题讨论】:

  • 请注意,加密数据(密文)在大多数情况下是二进制数据,因此您需要将密文转换为字符串格式 -> 使用 base64 编码获取字符串并对数据进行 base64 解码稍后解密。

标签: php libsodium


【解决方案1】:

发现了我的问题,一个简单的 print_r() 把我搞砸了。上面的代码按预期工作,我会尽快发布一些改进。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 2018-10-30
    • 2011-09-10
    相关资源
    最近更新 更多