PHP-javaScript-RSA 非对称加密

基于 jsencrypt.js 之 javaScript 加密,PHP解密。 (应用于登录注册)。前端后台数据交互需要进行加密之后传输使用,以保证系统数据的安全。非对称加密速度慢,所以只能加密较小的数据。可以在AES 基础上进行RSA 加密(将数据 AES 加密,在用RSA 加密 AES的密钥)。

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<script src='{{asset("js/jsencrypt.min.js")}}'></script>
<script>
var username = '1112223',
password = '123456';
function rsa(text, key) {
var encrypt = new JSEncrypt();
encrypt.setPublicKey(key);
var encrypted = encrypt.encrypt(text);
return encrypted;
}
$.ajax({
url:'http://www.you.com/test/rsa/public', // 发送请求获取 公钥
type:'post',
dataType:'json',
success:function(data) {
// data 返回的 public key
var en = rsa(password, data.result);
$.ajax({
url:'http://www.you.com/test/rsa/doLogin',
type:'post',
dataType:'json',
data:{password:en},
success:function(data) {
console.log(data);
}
});
}
});
</script>

PHP

确认是否有openssl 扩展

1
2
3
4
5
   $privKey = openssl_pkey_get_private($private_key);
$encrypted = base64_decode($encrypted); // jsencrypt, 默认使用base64 加密,所以需要解密
// Decrypt the data using the private key and store the results in $decrypted
openssl_private_decrypt($encrypted, $decrypted, $privKey); // $encrypted 需要解密的文本
return $decrypted;

生成私钥、公钥

1
2
3
4
5
6
7
8
9
10
11
12
13
$config = array(
"digest_alg" => "sha512",
"private_key_bits" => 4096,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$res = openssl_pkey_new($config);
openssl_pkey_export($res, $privKey);
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];

// 将私钥 $privKey , 和公钥 $pubKey 保存起来
file_put_contents('./cert_public.key', $pubKey);
file_put_contents('./cert_private.pem', $privKey);