Javascript RSA Library is from https://github.com/ziyan/javascript-rsa
PHP RSA Library is from http://phpseclib.sourceforge.net/
Example is from https://stackoverflow.com/a/10922491/5281854
My code (the browser still send the original text to the server):
<?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("
", "\\
", $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>
All the library files are correctly loaded. Can anyone tell me why the encryption does not work?
So I tried your code on my own local machine and ran into a few issues.
You're doing str_replace(" ", "\\ ", $publickey)
- I had to do str_replace(" ", "\\ ", $publickey)
or else I'd get a Uncaught SyntaxError: Unexpected token ILLEGAL
error in the javascript console.
Even after having done #1 I'm still getting a Uncaught TypeError: this.toRadix is not a function
error. I'm using 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/
That said, looking at your rsa.js... I still stand by my original statement that $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
should work assuming that the javascript errors can be overcome. Unfortunately, since I can't get past them (and I'm not interested in fixing a piece of code that hasn't been updated in three years) I can't verify. Do you actually have a working example, yourself, that doesn't produce errors in the JS console?