$res = openssl_pkey_new(array(
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
'digest_alg' => 'sha256'
));
//Made Public key compatible with cryptico.js
$detail = openssl_pkey_get_details($res);
$n = base64_encode($detail['rsa']['n']);
$e = bin2hex($detail['rsa']['e']);
$publicKey = "$n|$e";
openssl_pkey_export($res, $privateKey);
file_put_contents("public_key",$publicKey);
file_put_contents("private_key",$privateKey);
制造cryptico.js两处修改为在同一职位建议
my.publicKeyFromString = function(string)
{
var tokens = string.split("|");
var N = my.b64to16(tokens[0]);
var E = tokens.length > 1 ? tokens[1] : "03";
var rsa = new RSAKey();
rsa.setPublic(N, E);
return rsa
}
my.encrypt = function(plaintext, publickeystring, signingkey)
{
var cipherblock = "";
try
{
var publickey = my.publicKeyFromString(publickeystring);
cipherblock += my.b16to64(publickey.encrypt(plaintext));
}
catch(err)
{
return {status: "Invalid public key"};
}
return {status: "success", cipher: cipherblock};
}
现在,在客户端JS:
var publicKey = '';
var encrypted = cryptico.encrypt("plain text", publicKey);
var data = 'encrypted_post_var='+encrypted.chiper;
然后我通过AJAX POST发送数据,我可以证实,它已与$ _ POST [ “encrypted_post_var”]
被成功接收在PHP中:
$private = openssl_pkey_get_private(file_get_contents("private_key"));
//!!! THAT is the problem because here openssl_private_decrypt() return FALSE !!!
openssl_private_decrypt(base64_decode($_POST["encrypted_post_var"]), $decrypted, $privateKey);
2017-04-15
MTK