码迷,mamicode.com
首页 > 编程语言 > 详细

Java Web 登录采用非对称加密(RSA算法)

时间:2015-03-09 17:39:22      阅读:350      评论:0      收藏:0      [点我收藏+]

标签:

登录时采用md5或者base64神马的加密都是不可靠的,被抓包了还是可以模拟登录的,基本没啥用,只能说好过没有...

接下来跟大家介绍下如何采用非对称加密,非对称加密的过程其实就是和https加密原理一样,我的处理过程是这样:

a. 在登录页面生成公钥和私钥,将私钥存在sesion中

b.公钥用于前端页面对数据进行加密

c.将数据传输给后台,后台从session中拿到私钥,然后对数据进行解密,把session中的私钥删除

下面简单记录下实现过程,具体的工具类RSAUtils.java的实现不在这里细说。


1、在JSP中生成公钥和私钥,将公钥放在session中:

   HashMap<String, Object> map = RSAUtils.getKeys();
   //生成公钥和私钥  
   RSAPublicKey publicKey = (RSAPublicKey) map.get("public");
   RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");
 //私钥保存在session中,用于解密
   session.setAttribute("privateKey", privateKey);
   //公钥信息保存在页面,用于加密
   String publicKeyExponent = publicKey.getPublicExponent().toString(16);
   String publicKeyModulus = publicKey.getModulus().toString(16);
   request.setAttribute("publicKeyExponent", publicKeyExponent);
   request.setAttribute("publicKeyModulus", publicKeyModulus);

2、对数据进行加密,用到的前端js工具封装在RSA.js中,需引入到页面。

   RSAUtils.setMaxDigits(200);
   var key = new RSAUtils.getKeyPair("${publicKeyExponent}", "", "${publicKeyModulus}");
   var encrypedPwd = RSAUtils.encryptedString(key,orgPwd.split("").reverse().join(""));
其中,orgPwd为原始数据,这里是我的密码。


3、后台对接收到的数据进行解密。

	String password=request.getParameter("password");
<span style="white-space:pre">	</span>RSAPrivateKey privateKey = (RSAPrivateKey)request.getSession().getAttribute("privateKey");
			if(privateKey!=null){
				long time1 = System.currentTimeMillis();
				password = RSAUtils.decryptByPrivateKey(password, privateKey);
				log.info("decrypt cost time:"+(Double)((System.currentTimeMillis()-time1)/1000d) +"s");
				request.getSession().removeAttribute("privateKey");
			}


特别注意事项:RSAUtils.java中用到org.bouncycastle.jce.provider.BouncyCastleProvider,部署在服务器上时需做如下两项配置:

a. 修改jdk目录下的 /jre/lib/security/java.security,增加如下配置:

技术分享

b. 放bcprov-jdk16-146.jar 到 jdk目录下的/jre/lib/ext 下。

在eclipse中开发调试倒是不需要,但部署上服务器时需要,切记!


附件:

1. RSA.js http://pan.baidu.com/s/1ntr99LR

2.RSAUtils.java http://pan.baidu.com/s/1o6l1Wnw

3.bcprov-jdk16-146.jar http://pan.baidu.com/s/1i3EIw0P




Java Web 登录采用非对称加密(RSA算法)

标签:

原文地址:http://blog.csdn.net/linshutao/article/details/44062539

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!