当前位置: 首页 > 工具软件 > Vdt.js > 使用案例 >

RSA 前端JS加密 PHP解密

徐涵亮
2023-12-01

在线生成加密对网站:

http://web.chacuo.net/netrsakeypair

前端代码:rsa.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">

<script src="https://passport.cnblogs.com/scripts/jsencrypt.min.js"></script>
<script src="http://cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script>

</head>



前端页面上对应的input输入框为:
密码:<input name="password" id="password" value="123456"><br/>
加密后的密文(base64):<br/>
<textarea id="input" name="input" type="text" rows=6 cols=70></textarea><br/>
<input id="testme" type="button" value="加密"/><br/>

<script>
var pubkey='-----BEGIN PUBLIC KEY-----';
pubkey+='MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCytYlGIkLH8Vp6FY72PSfjnlkw';
pubkey+='IkR6r8Iw6DJvSwVil8ww88hNx3sf86CeE1ttoyIJO1jV52Oijr6P5cvtG3oG9J0U';
pubkey+='Lp+wrJmtiEBJkAKuK/45+D65boBKrI8ye/AGiQe0tm611JVGDMFyBJUKlAVQjsrk';
pubkey+='kjf93uzY562B448U4QIDAQAB';
pubkey+='-----END PUBLIC KEY-----';

$("#testme").click(function(){
	var encrypt = new JSEncrypt();
	encrypt.setPublicKey(pubkey);
	var encrypted = encrypt.encrypt(JSON.stringify({"encrypt": "yes", "password": $("#password").val()}));
	$('#input').val(encrypted);
})

</script>



</html>

后端面代码:rsa.php

<?php

$text = "MhWNrb+a3a0gDHow7AEoe6QUgDUOSTcwchC4Iv/YTZUiW6HXVUX+jeJVE9QW6JlVFopDvVNUFBNa8kaTjM8JRa5V2H5/0E3rRRlIh7s5jjJKX6dHidtTiAPJrJh/PrvkhVN49n2Zp3VyV/zCBGsICfWZWQMQwQcL9tpVlY4PgoU=";

var_dump(getRSAEncode($text));


function getRSAEncode($text)
{
        $private_key='-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCytYlGIkLH8Vp6FY72PSfjnlkwIkR6r8Iw6DJvSwVil8ww88hN
x3sf86CeE1ttoyIJO1jV52Oijr6P5cvtG3oG9J0ULp+wrJmtiEBJkAKuK/45+D65
boBKrI8ye/AGiQe0tm611JVGDMFyBJUKlAVQjsrkkjf93uzY562B448U4QIDAQAB
AoGAJ3eLEQeY+wI06phfQcdgy1aZuNUgjX3KY7WsCcMmNc9zY247Ut4WtYg+9Rou
S2jHKAXIyTi4WtqugCYOYtd6G7epam2V0q+RrIVwGJKXJzoR4RLYmDITAOlU/9H9
0PohTg11NMP3UjiqFWE5QG7vDFQBY9CrBFHifhJLWReW9MkCQQDWEAzSAoURyAaz
XYgoWlkYYVnhX5/IHXY+ONR2RUwY9aceBJ2WD4OPoccu3bOtKqf95i2dXiEILJWE
Em3tJIXVAkEA1bhjWHh7TnktXpt+DDEGSKES1vImHdyQc7dIgWW62ric8GV05ar2
SW949+UaY7prGdpKg2yQHv+6DKfMG7Nc3QJAeyHsXfk5FktbH13T7nJaAZ4uF2fr
/y6DT7Nc81NVPJ5BrRC2nRT7dml2q8y3iAqba382CemVUqBiuP/o35o8qQJBAJrP
+17Nv3xjuOKsPg00wfmAfDYpqES/TgAUhzf8afMgAcb9p0Tqp4cgcX8YfRo6onRS
tOEolelukuWx8t8p+R0CQBrMG0l4bvHH+nBXKGUkD8oruAKADUs33+vdt39BdhyI
Fnb+8RvK/z3S+JnSFdxCKB8tcKbyuJKC4L5Vz5r0Pm4=
-----END RSA PRIVATE KEY-----';

			
	//私钥解密 
	openssl_private_decrypt(base64_decode($text),$decrypted,$private_key); 
	$encrypt_exist=false;
	if(!empty($decrypted)) {
		$arr = json_decode($decrypted, true);
		if(array_key_exists("encrypt",$arr)) {
			if($arr['encrypt']=="yes") $encrypt_exist=true;
		}
	}
	if(!$encrypt_exist) die("抱歉!数据提交错误!");
	//继续后续处理
	return $arr['password'];
}

 

 类似资料: