PHP - RSA前端公钥加密后台秘钥解密

在开发中,前端向后台传输一些敏感数据时,如果不做一些数据的加密等,会以明文的形式进行传输,这样就把一些信息暴露到外面,下面要是一下通过RSA加密的方式进行传输:
1.首先前端加密需要用到js插件:jsencrypt.js下载地址

前端部分代码如下:【RSA公钥秘钥可通过在线工具获得】

//公钥
var pubkey = '-----BEGIN PUBLIC KEY-----';
pubkey += 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAbfx4VggVVpcfCjzQ+nEiJ2DL';
pubkey += 'nRg3e2QdDf/m/qMvtqXi4xhwvbpHfaX46CzQznU8l9NJtF28pTSZSKnE/791MJfV';
pubkey += 'nucVcJcxRAEcpPprb8X3hfdxKEEYjOPAuVseewmO5cM+x7zi9FWbZ89uOp5sxjMn';
pubkey += 'lVjDaIczKTRx+7vn2wIDAQAB';
pubkey += '-----END PUBLIC KEY-----';

//公钥加密
var encrypt = new JSEncrypt();
encrypt.setPublicKey(pubkey);
var encrypted = encrypt.encrypt(JSON.stringify({"encrypt": "yes", "password": '123456'}));
console.log(encrypted);

2.php后端秘钥解密,部分代码如下:

//私密
$pra_key = '-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDAbfx4VggVVpcfCjzQ+nEiJ2DLnRg3e2QdDf/m/qMvtqXi4xhw
vbpHfaX46CzQznU8l9NJtF28pTSZSKnE/791MJfVnucVcJcxRAEcpPprb8X3hfdx
KEEYjOPAuVseewmO5cM+x7zi9FWbZ89uOp5sxjMnlVjDaIczKTRx+7vn2wIDAQAB
AoGAZzUWajxKTZeJqh5FjBgmwZi5M7voFynZAjRWAkCkqZye0FfY7e70kA92C1AL
aVqySnNr4WYZuGorEeOFGqHIv1XSowTLgfLkVBZ/SXiep2QYJrR0YevjysvLnTfb
mrdWCqWSj+0AlQg+AvDA/qtvBVMxKymbpo+4bj5H2pPPZ1ECQQDi1PwJQJBYPbpL
vGmP3AmWg467tCeQ+aJGgtQTOK5BH+p0BWFVDX583R437vllkKI8EXgZfqQfsQcj
7XUAXyZVAkEA2SyFbO8roH9JLrEoxxKGeiGZvhPfNl9nXLhX0OFS0ywQaVBJno39
9W5bX5iP5Jzeb3UWsZ/TxzhGc/b4WjAlbwJBAOFuIn1feRT5Y+hY++BJIg4/+N57
EMd4ENpas0HXFvcKLQvZPP42Rvr5FksoaRuTPmjMQ7uyrJICccI3AAy6g3ECQQDE
AyH9+zRmLNxRj0advsOvUcpgu7DYc21oS12/Qs+tl3TMiNGZkNDphwxjkOA217sP
4B92fCn6AnncSslHJXNzAkBo6ujxqIfrZMOG3ON9nXxkWlq39GFS6CzXWscHA3Xz
FMVT1WWU3FR2Kf2QSKiMGv02YcI2xfowim3JnT6600N0
-----END RSA PRIVATE KEY-----';
//获取加密后的密文
$cryptograph = $_POST['cryptograph'];
//私钥解密
openssl_private_decrypt(base64_decode($cryptograph),$decrypted,$pra_key);
var_dump($decrypted);

在线工具:秘钥对在线生成工具:http://web.chacuo.net/netrsakeypair

添加新评论