项目中需要在用户登录的时候对用户信息在前端进行加密,下面将用到的方法进行总结一下
1.rsa加密,需要下载jsencrypt.min.js
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Login</title>
<script src="jquery-1.10.2.min.js"></script>
<script src="jsencrypt.min.js"></script>
<script type="text/javascript">
$(function () {
//公钥需要保密,当然我给的是错误的,下方改成你的公钥即可
var publicKey = "DEFEMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCo7omtMpwfca4fedqLyep8eomOKxEeBqWeMi+10bDanlGfHVbDy3emVPFAKDIr2T6osqxrOumpvYt2vUDR+oZCBNRBfjDCAn5GFxmqVuHwRthIDlCNG+WPUXm7jIP1F94ajh4OXfe0hatTa029N/nyqDGW/3B4KBMq7NYTF/8jpQIDAQABEWFEF";
var encrypt = new JSEncrypt();
encrypt.setPublicKey(publicKey);
$("#btn").click(function () {
document.getElementById('message').innerHTML += "明文:" + $("#tra").val() + '<br/>';
var data = encrypt.encrypt($("#tra").val());
document.getElementById('message').innerHTML += "加密:" + data + '<br/>';
var data = data.replace(/\+/g, '%2B');
document.getElementById('message').innerHTML += "传输:" + data + '<br/><br/>';
});
});
</script>
</head>
<body>
<div>
<input type="button" id="btn" value="加密" /> <input id="tra" />
<hr />
<div id="message"></div>
</div>
</body>
</html>
2.sha256加密,需要下载sha256.js
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Login</title>
<script src="jquery-1.10.2.min.js"></script>
<script src="sha256.js"></script>
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
var data = $("#sha").val();
document.getElementById('message').innerHTML += "明文:" + data + '<br/>';
data = sha256_digest(data);
document.getElementById('message').innerHTML += "加密:" + data + '<br/>';
});
});
</script>
</head>
<body>
<div>
<input type="button" id="btn" value="加密" /> <input id="sha" />
<hr />
<div id="message"></div>
</div>
</body>
</html>