gpt4 book ai didi

php - 在 PHP 中加密消息,在 JavaScript 中解密

转载 作者:行者123 更新时间:2023-11-30 13:26:00 24 4
gpt4 key购买 nike

我想用 php 加密一条消息,但在客户端,我想用 javascript 来解密它。我试过 Blowfish(使用 mcrypt ),但我发现 php 回显非字母数字字符和 Javascript 显示字母数字。我正在使用 ajax,这样页面就不会重新加载。

我测试了来自 http://aam.ugpl.de/?q=node/1060 的代码和 http://www.php-einfach.de/blowfish_en.php#ausgabe .

感谢任何帮助。

编辑:我使用 Diffie-Hellman 来计算随机生成的数字 a 和 b 的 key 。以下是 php 代码的结果

class Encryption
{
const CYPHER = 'blowfish';
const MODE = 'cbc';
const KEY = '26854571066639171754759502724211797107457520821';

public function encrypt($plaintext)
{
$td = mcrypt_module_open(self::CYPHER, '', self::MODE, '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, self::KEY, $iv);
$crypttext = mcrypt_generic($td, $plaintext);
mcrypt_generic_deinit($td);
return $iv.$crypttext;
}

public function decrypt($crypttext)
{
$plaintext = '';
$td = mcrypt_module_open(self::CYPHER, '', self::MODE, '');
$ivsize = mcrypt_enc_get_iv_size($td);
$iv = substr($crypttext, 0, $ivsize);
$crypttext = substr($crypttext, $ivsize);
if ($iv)
{
mcrypt_generic_init($td, self::KEY, $iv);
$plaintext = mdecrypt_generic($td, $crypttext);
}
return $plaintext;
}
}

$encrypted_string = Encryption::encrypt('this is a test');
$decrypted_string = Encryption::decrypt($encrypted_string);

echo "encrypted: $encrypted_string<br>";
echo "decrypted: $decrypted_string<br>";

encrypted: µ˜?r_¿ÖŸŒúw‰1‹Žn!úaH
decrypted: this is a test

最佳答案

这个来自几个斯坦福学生的 javascript AES 加密库是我见过的最好的:

http://crypto.stanford.edu/sjcl/

但请注意他们的警告:

We believe that SJCL provides the best security which is practically available in Javascript. (Unfortunately, this is not as great as in desktop applications because it is not feasible to completely protect against code injection, malicious servers and side-channel attacks.)

更新:

在PHP中,加密后使用base64_encode(),解密前使用base64_decode()。这样,它将使用可安全传输的字符进行渲染。在浏览器中,使用 atob()btoa()

关于php - 在 PHP 中加密消息,在 JavaScript 中解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8456288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com