我使用了此answer中的加密
和解密
函数使用 Three-pass protocol 实现消息传递使用河豚密码。
我尝试使用交换加密/解密。也就是说,
$tmp = encrypt($input, $key1);
$tmp = encrypt($tmp, $key2);
$tmp = decrypt($tmp, $key1);
$dec2 = decrypt($tmp, $key2);
但是它不起作用。我使用了一个键而不是 2 个不同的键,它可以工作(必须!)。
所以我使用这些功能的方式没有问题,但我就是无法使用两个键来使用它。
我做错了什么吗?难道这不行,还是有其他办法?
或者,有什么办法可以用 Java 做到这一点吗?
编辑:对于那些不了解该过程的人,三通协议(protocol)是一种无需发送 key 即可发送加密消息的方法。所以程序是
发送者使用 key1 加密并发送
接收方使用key2加密并发回
发送者使用 key1 解密并发回
接收方使用key2解密得到原始消息
您可以看到 key 没有交换,但消息仅以加密形式发送。这就是重点。
最佳答案
使用此线程中用户提供的 XOR 函数
Encrypt/decrypt with XOR in PHP
function xor_this($string,$key) {
// Our plaintext/ciphertext
$text =$string;
// Our output text
$outText = '';
// Iterate through each character
for($i=0;$i<strlen($text);)
{
for($j=0;($j<strlen($key) && $i<strlen($text));$j++,$i++)
{
$outText .= $text{$i} ^ $key{$j};
//echo 'i='.$i.', '.'j='.$j.', '.$outText{$i}.'<br />'; //for debugging
}
}
return $outText;
}
//The sender chooses a private encryption key s and a corresponding decryption key t. The sender encrypts the message m with the key s and sends the encrypted message E(s,m) to the receiver.
//The receiver chooses a private encryption key r and a corresponding decryption key q and super-encrypts the first message E(s,m) with the key r and sends the doubly encrypted message E(r,E(s,m)) back to the sender.
//The sender decrypts the second message with the key t. Because of the commutativity property described above D(t,E(r,E(s,m)))=E(r,m) which is the message encrypted with only the receiver's private key. The sender sends this to the receiver.
$senderkey=base64_encode('chicken');
$receiverkey=base64_encode('ardvark');
$itemwewanttoshare='hello darling';
echo'$itemwewanttoshare: '.$itemwewanttoshare.'<BR>';
$packet1=xor_this($itemwewanttoshare,$senderkey);
echo'$packet1: '.$packet1.'<BR>';
$packet2=xor_this($packet1,$receiverkey);
echo'$packet2: '.$packet2.'<BR>';
$packet3=xor_this($packet2,$senderkey);
echo'$packet3: '.$packet3.'<BR>';
$packet4=xor_this($packet3,$receiverkey);
echo'$packet4: '.$packet4.'<BR>';
你明白了
$itemwewanttoshare: hello darling
$packet1: 1W6 TS>
$packet2: hNwRVtq|ing
$packet3: 1=&M"TS>
$packet4: hello darling
<小时/>
编辑添加
为了简单起见,我对 key 进行了 base64 处理。使用变化更多的 key ,结果会更复杂。
使用mcrypt_create_iv(40)
来创建你的 key ,你最终会得到这样的东西
$senderkey='<²#H[Ô\´(µÑ/KÀ®"熺¥ç|Ëvr%O›eu$nºbe';
$receiverkey='Øh\5PÀKO[ù¬òZH‰•Ê¬h/¥nëk¾ðéíPÄ"Uü';
这会将输出更改为
$itemwewanttoshare: hello darling
$packet1: T§ÞO'{§õ.®ÝF¥
$packet2: —?¶+¦6®½– þ
$packet3: «ý0Zpe¢ò"!<
$packet4: hello darling
<小时/>
编辑2
Duskwuff 提出了一个很好的观点。 $itemwewanttoshare
应该由系统(程序)创建,而不是用户创建的项目。此方法可用于建立共享加密 key ,发送者和接收者都可以使用该共享加密 key 来加密进一步的通信。发送者将生成 key ,然后这将是 itemwewanttoshare ,从而允许双方知道加密 key 而无需直接传递它。
关于java - 有没有办法在php中使用交换加密?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28309963/