Sodium Crypto盒封打开在PHP中不起作用

时间:2019-03-19 19:04:26

标签: php public-key-encryption libsodium

所以我试图使libsodium的sodium_crypto_box_sealsodium_crypto_box_seal_open工作,但是由于某种原因,开放失败了,我无法弄清楚为什么。

因此,在我试图使之正常工作的所有过程中,我构建了一个测试系统,该系统可以测试单个PHP文件跨服务器的工作方式。

<pre>
<?php
/*** Client Sending ***/
// saved argument
$remotePublic = "DXOCV4BU6ptxt2IwKZaP23S4CjLESfLE+ng1tMS3tg4=";

// create out key for this message
$key = sodium_crypto_box_keypair();

// encrypt our message using the remotePublic
$sealed = sodium_crypto_box_seal("This is a test", base64_decode($remotePublic));
$send = json_encode((object)array("pub" => base64_encode(sodium_crypto_box_publickey($key)), "msg" => base64_encode($sealed)));
echo "Sending : {$send} \r\n";

/*** Server Setup ***/
$payload = json_decode($send);
$apps = 
array (
  'test' => 
  array (
    'S' => 'lv/dT3YC+Am1MCllkHeA2r3D25HW0zPjRrqzR8sepv4=',
    'P' => 'DXOCV4BU6ptxt2IwKZaP23S4CjLESfLE+ng1tMS3tg4=',
  ),
);

/*** Server Opening ***/
$msg = $payload->msg;
$key = sodium_crypto_box_keypair_from_secretkey_and_publickey(base64_decode($apps['test']['S']), base64_decode($apps['test']['P']));
$opened = sodium_crypto_box_seal_open(base64_decode($msg), $key);
echo "Opened : {$opened} \r\n";

/*** Server Responding ***/
$sealedResp = base64_encode(sodium_crypto_box_seal("We Got your message '{$opened}'", base64_decode($payload->pub)));
echo "Responding : {$sealedResp}\r\n";

/*** Client Receiving ***/
$received = sodium_crypto_box_seal_open(base64_decode($sealedResp), $key);
echo "Received : {$received}\r\n";

/*** Sanity Checking ***/
if($received == "We Got your message 'This is a test'"){
    echo "Test Successfull.\r\n";
}else{
    echo "Test Failed got '{$received}' is not \"We Got your message 'This is a test'\"\r\n";
}
?>
</pre>

输出为:

Sending : {"pub":"DS2uolF5lXZ1E3rw0V2WHELAKj6+vRKnxGPQFlhTEFU=","msg":"VVYfphc2RnQL2E8A0oOdc6E\/+iUgWO1rPd3rfodjLhE+slEWsivB6QiaLiMuQ31XMP\/1\/s+t+CSHu8QukoY="} 
Opened : This is a test 
Responding : cvDN9aT9Xj7DPRhYZFGOR4auFnAcI3qlwVBBRY4mN28JmagaR8ZR9gt6W5C0xyt06AdrQR+sZFcyb500rx6iDTEC4n/H77cUM81vy2WfV8m5iRgp
Received : 
Test Failed got '' is not "We Got your message 'This is a test'"

1 个答案:

答案 0 :(得分:3)

这里有两个问题。

首先-在此步骤的“服务器打开”下:

$opened = sodium_crypto_box_seal_open($msg, $key);

$msg仍采用Base64编码,因此尝试对其进行解密将失败。

第二个-"pub"的{​​{1}}字段中包含的公钥是$send生成的随机密钥对的公钥,不是sodium_crypto_box_keypair()$remotePublic中的对相同的公钥。稍后在应用程序中调用$apps会覆盖此密钥,从而使原始消息无法恢复。