【发布时间】: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 解码稍后解密。