在通常的http协议的网站中直接提交数据可以通过信息抓取从而暴露提交者所提交的信息,特别是注册时的密码和登录时的密码容易被泄露。那么怎么防止这种现象呢?很多人会想到加密技术,对没错,本文所讲的就是使用rsa非对称加密技术进行数据提交,由客户获取后台所产生的公钥对提交字段进行加密,用户提交后再由后台所产生的私钥进行解密。这里以用户登录时对用户密码进行加密为列,下面直接上代码:
前端js代码:
<script type="text/javascript" src="js/security.js"></script>
<script type="text/javascript">
$(function(){
$('#subt').click(function(){
var name = jQuery('#loginName').val();
var password =jQuery('#loginPwd').val();
if(name==null||name==""){
alert("用户名不得为空!");
return;
}
if(password==null||password==""){
alert("密码不得为空!");
return;
}
jQuery.ajax({
type:"post",
url:"loginset",
success:function(rd){
if(rd!=null){
//加密模
var Modulus = rd.split(';')[0];
//公钥指数
var public_exponent = rd.split(';')[1];
//通过模和公钥参数获取公钥
var key = new RSAUtils.getKeyPair(private_exponent, "", Modulus);
//颠倒密码的顺序,要不然后解密后会发现密码顺序是反的
var reversedPwd = password.split("").reverse().join("");
//对密码进行加密传输
var encrypedPwd = RSAUtils.encryptedString(key,reversedPwd);
jQuery('#subPwd').val(encrypedPwd);
jQuery('#loginPwd').val("");
jQuery('#login').submit();
}
}
})
})
})
</script>
前端html代码:
登录 |
用户名: |
密 码: |
RSAUtils rsa = new RSAUtils();
//生成公钥和密钥
Map<String,Object> keyMap = rsa.createKey();
RSAPublicKey publicKey = (RSAPublicKey) keyMap.get(“publicKey”);
RSAPrivateKey privateKey = (RSAPrivateKey) keyMap.get(“privateKey”);
//js通过模和公钥指数获取公钥对字符串进行加密,注意必须转为16进制
//模
String Modulus = publicKey.getModulus().toString(16);
//公钥指数
String Exponent = publicKey.getPublicExponent().toString(16);
//私钥指数
String private_exponent = privateKey.getPrivateExponent().toString();
HttpSession session = request.getSession();
//java中的模和私钥指数不需要转16进制,但是js中的需要转换为16进制
session.setAttribute(“Modulus”,publicKey.getModulus().toString());
session.setAttribute(“private_exponent”,private_exponent);
String strSet = Modulus+";"+Exponent;
response.setContentType(“text/html;charset=UTF-8”);
response.setCharacterEncoding(“UTF-8”);
PrintWriter out = response.getWriter();
out.write(strSet);
out.flush();