我正在尝试从客户端到服务器进行非对称加密,客户端拥有公钥,服务器拥有私钥。
在客户端,我在 javascript 中使用 JSEncrypt 来使用我的公钥进行加密。从那里我使用 AJAX 将加密数据发送到我的 PHP 脚本。我尝试用它openssl_private_decrypt()
来解密数据,但它总是返回false。我试过告诉它期待不同的填充,即使我确定它是 PKCS1。
有人可以告诉我我做错了什么吗?
以下是所有相关代码:
JAVASCRIPT:
function getpubkey(){ //Gets Public Key from server
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
pubkey = this.responseText;
}
};
xmlhttp.open("POST", "PHP/ajax.php", false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("do=getpub");
}
function encryptdata(plaintext){ //Encrypts argument with Public Key
var encrypt = new JSEncrypt();
encrypt.setPublicKey(pubkey);
var encrypted = encrypt.encrypt(plaintext);
return encrypted;
}
function login(){ //Sends login data to server and displays response on page
getpubkey();
var encuser = encryptdata(document.getElementById('username').value);
var encpass = encryptdata(document.getElementById('password').value);
encuser = window.btoa(encuser);
encpass = window.btoa(encpass);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
document.getElementById('maincontent').innerHTML = this.responseText;
}
};
xmlhttp.open("POST", "PHP/ajax.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("do=login¶m1="+encuser+"¶m2="+encpass);
}
PHP (ajax.php):
if (!isset($_POST['do'])){
header("Location: ../index.php");
die();
}
$do = $_POST['do'];
if(isset($_POST['param1'])){
$param1 = $_POST['param1'];
}
if(isset($_POST['param2'])){
$param2 = $_POST['param2'];
}
$allow = 1;
require("../KEYS/priv.php"); //Contains $priv which holds the private key
if(openssl_private_decrypt(base64_decode($param1), $username, $priv, OPENSSL_PKCS1_PADDING)){
$return = $username;
}
else{
$return = "Decrypt Failed";
}
if(isset($return)){
echo $return;
}
priv.php:
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