为什么 Javascript 没有加密我的表单?

Why the Javascript did not encrypt my form?

Javascript RSA 库来自 https://github.com/ziyan/javascript-rsa

PHP RSA 库来自 http://phpseclib.sourceforge.net/

例子来自

我的代码(浏览器还是把原文发给服务器):

<?php
include('Crypt/RSA.php');
session_start();
$rsa = new Crypt_RSA();
if(isset($_POST['password'])){
    echo $_POST['password'];
    echo 1;
    $rsa->loadKey($_SESSION['privatekey']);
    echo $rsa->decrypt($_POST['password']);
    exit();
}
extract($rsa->createKey(4096));

$_SESSION['privatekey']=$privatekey;
$publickey=str_replace("\n", "\\n", $publickey);
?>
<!DOCTYPE html>
<html>
<head>
<script language="JavaScript" type="text/javascript" src="jsbn.js"></script>
<script language="JavaScript" type="text/javascript" src="rsa.js"></script>
<script language="JavaScript">

    function encryptData(){

        //Don't forget to escape the lines:
        var pem = "<?php echo $publickey; ?>";
        var key = RSA.getPublicKey(pem);
        element=document.getElementById('password');
        element.value=RSA.encrypt(element.value, key);
    }
</script>
</head>
<body>

<form method='POST' id='txtAuth' onsubmit='encryptData()'>
    <input type='text' name='username'/>
    <input type='password' name='password' id='password' placeholder="password"/>
    <input name='submit' type='submit' value='Submit'>
</form>
</body>
</html>

所有库文件都已正确加载。谁能告诉我为什么加密不起作用?

所以我在自己的本地机器上尝试了您的代码,运行 遇到了一些问题。

  1. 你正在做 str_replace("\n", "\\n", $publickey) - 我必须做 str_replace("\r\n", "\\n", $publickey) 否则我会在 javascript 控制台中收到 Uncaught SyntaxError: Unexpected token ILLEGAL 错误.

  2. 即使完成#1,我仍然收到 Uncaught TypeError: this.toRadix is not a function 错误。我正在使用 https://raw.githubusercontent.com/ziyan/javascript-rsa/master/src/jsbn.js and https://raw.githubusercontent.com/ziyan/javascript-rsa/master/src/rsa.js and I haven't really modified your code at all. Try it out for yourself: http://www.frostjedi.com/terra/so/

就是说,看看您的 rsa.js...我仍然坚持我最初的说法,即假设可以克服 javascript 错误,$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); 应该可以工作。不幸的是,由于我无法通过它们(并且我对修复一段三年未更新的代码不感兴趣)我无法验证。您自己是否真的有一个不会在 JS 控制台中产生错误的工作示例?