web登陆用户名密码加密

以前一直没关注过web应用登陆密码加密的问题,这两天用appscan扫描应用,最严重的问题就是这个了,提示我明文发送密码。这个的确很不安全,之前也大概想过,可是没有具体研究过,都不了了之,此次借这个机会,终于搞定了这个问题。javascript

首先,有很多帖子说在客户端用js对密码进行md5摘要,而后提交给登陆处理的url。这种作法无非是自欺欺人,就算别人抓包抓不到你原始密码,用这个md5后的密码同样能够模拟登陆系统,无非稍微安全了一点点,也就是直接经过登陆页无法直接输入用户名密码来登陆,可是人家的手段你知道有啥呢?用程序模拟登录也不是什么太难的事情。html

https固然也是个选择,可是对于通常应用来讲,还须要生成密钥之类的,还须要拿去给那些认证机构签名,麻烦不说,银子是必须的。若是说让用户安装证书,应用系统还能够,网站就不太现实了,毕竟不是全部用户都有那么高的计算机操做水平,就算有,人家一用感受这么麻烦,也不见得去操做。java

此次专心搜索了1个小时,仍是以为非对称加密比较靠谱,有一些RSA加密的文章值得借鉴。这里向这些文章做者致敬,我参考可不仅一篇文章,由于问题多多的。废话到此结束,说说个人处理方式吧。git

加密解密的流程:web

 a)在login.jsp中,加入一段java代码,生成公钥和私钥,私钥对象保存在session中;公钥中,我把Exponent, modulus放到request的attribute中,并在页面上输出给js加密函数,用于密码加密。使用security.js的功能加密ajax

[javascript]  view plain  copy
  在CODE上查看代码片 派生到个人代码片
  1. var key = new RSAUtils.getKeyPair("${publicKeyExponent}""""${publicKeyModulus}");  
  2.   
  3.        var reversedPwd = password.split("").reverse().join("");//js里面是反序的字符串,不知道为啥  
  4.        var encrypedPwd = RSAUtils.encryptedString(key,reversedPwd);  

b)在点击提交按钮时,调用登录js函数。这个函数是用ajax方式将用户名,密码提交给登录处理url的。在提交以前,先利用a步骤中的公钥Exponent,和modulus,对密码进行加密,而后再发送给服务器端。算法

c)在登录处理url中,(我是login.action),从session中取得私钥对象,对密码进行解密。随后的步骤都同样了,到库里去查询之类的,不细说了。json

下面说说我处理的步骤和遇到的主要问题。api


1.只能使用RSA这种非对称加密,才能让密码破解成为仅仅“理论上”的可能。因此决定使用这种加密方式。数组

2.寻找合适的客户端javascript加密代码。这个我是不太懂了,只能去找。最后找到了security.js。网上有些文章用的3个文件,BigInt.js,RSA.js还有个啥来着,Barrett.js这3个来实现,开始我用了。可是和服务端配合不了(我本身的问题),结果后来找到这个security.js,其实是把这个3个js都封装到1个里面了,并且最后修改时间是2010年,比较新,就用这个吧。那3个js文件应该也是能用的。

3.在服务器端生成公钥和私钥,这个原本想对简单,代码可参考的不少。可是我遇到的问题很多,解密的时候老是出错。

   问题一:在login.jsp中,公钥的Exponent,和modulus输出格式问题

       开始老是什么:长度过大,必须以0开始之类的异常。我想到极可能是js加密和纯java加密那些地方不一样致使的。后来发现,原来是我公钥的Exponent,和modulus输出直接用的toString()方法,实际上应该用toString(16),用16进制输出,由于在security.js中,那个

RSAUtils.getKeyPair(publicKeyExponent, "", ${publicKeyModulus);方法内部,明显是从16进制进行转换的。改完后应该是这样:

     

[java]  view plain  copy
  在CODE上查看代码片 派生到个人代码片
  1. String publicKeyExponent = publicKey.getPublicExponent().toString(16);//16进制  
  2.     String publicKeyModulus = publicKey.getModulus().toString(16);//16进制  
  3.     request.setAttribute("publicKeyExponent", publicKeyExponent);  
  4.     request.setAttribute("publicKeyModulus", publicKeyModulus);  

 问题二:有个什么Padding之类的异常,是RSA算法中前面补齐的问题,缘由时js和java默认的RSA算法不一致。

     通过分析,用RSA其余的provider能够解决此问题,因而在生成密码对的代码中,使用了

  

[java]  view plain  copy
  在CODE上查看代码片 派生到个人代码片
  1. KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"new org.bouncycastle.jce.provider.BouncyCastleProvider());    

这个的补齐方式和js的就一致了。

问题三:provider的认证问题

  刚用上,感受能经过了,可是立刻就是一个异常:jce cannot authenticate the provider bc。意思好理解,就是没通过认证。怎么让他经过呢,结果我在运行应用服务器的javahome\jre\lib\security\java.security文件中添加了以下代码:

[java]  view plain  copy
  在CODE上查看代码片 派生到个人代码片
  1. security.provider.11=org.bouncycastle.jce.provider.BouncyCastleProvider  
11是序号,顺着它原来的加就能够了。
感受上ok了,启动一下看看,仍是那个问题。这个问题是我在jboss-eap-6.2上出现的。其余的应用服务器可能比较简单些(好比直接放到服务器的lib下)。

因而查jboss的资料,终于找到了,说是在jboss中,不能让这个provider的jar包在应用的lib下,须要使用全局的jar包。若是使用maven,那必须让这个包的scope是provided;(反正别让BouncyCastle这个jar包打入到war里面就能够)。须要在eap6.2下进行配置:

在jboss_home/modules下创建目录org\bouncycastle\main,在main目录中,放入bcprov-jdk16-1.46.jar,并加入module的配置文件module.xml,内容以下:

 

[html]  view plain  copy
  在CODE上查看代码片 派生到个人代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <module xmlns="urn:jboss:module:1.1" name="org.bouncycastle">  
  3.     <resources>  
  4.         <resource-root path="bcprov-jdk16-1.46.jar"/>  
  5.     </resources>  
  6.     <dependencies>  
  7.         <module name="javax.api" slot="main" export="true"/>  
  8.     </dependencies>  
  9. </module>  
还须要在web应用的META-INF\MANIFEST.MF中加入Dependencies: org.bouncycastle

我是maven工程,须要配置pom:

[html]  view plain  copy
  在CODE上查看代码片 派生到个人代码片
  1. <plugin>  
  2.             <artifactId>maven-war-plugin</artifactId>  
  3.             <version>${version.war.plugin}</version>  
  4.             <configuration>  
  5.                <!-- Java EE 6 doesn't require web.xml, Maven needs to catch up! -->  
  6.                <failOnMissingWebXml>true</failOnMissingWebXml>  
  7.                <version>3.0</version>  
  8.                <archive>  
  9.                     <manifestEntries>  
  10.                     <Dependencies>org.bouncycastle</Dependencies>  
  11.                     </manifestEntries>  
  12.                 </archive>  
  13.             </configuration>  
  14.               
  15.          </plugin>  

主要是archive节点的配置,这样打包后MANIFEST.MF的内容就会变了

不能传附件可咋整呢?贴代码吧:

login.jsp

[javascript]  view plain  copy
  在CODE上查看代码片 派生到个人代码片
  1. <script src="js/lib/security.js" type="text/javascript"></script>  
  2. <script type="text/javascript">  
  3.     <%  
  4.         HashMap<String, Object> map = RSAUtils.getKeys();    
  5.         //生成公钥和私钥    
  6.         RSAPublicKey publicKey = (RSAPublicKey) map.get("public");    
  7.         RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");  
  8.           
  9.         session.setAttribute("privateKey", privateKey);//私钥保存在session中,用于解密  
  10.           
  11.         //公钥信息保存在页面,用于加密  
  12.         String publicKeyExponent = publicKey.getPublicExponent().toString(16);  
  13.         String publicKeyModulus = publicKey.getModulus().toString(16);  
  14.         request.setAttribute("publicKeyExponent", publicKeyExponent);  
  15.         request.setAttribute("publicKeyModulus", publicKeyModulus);  
  16.     %>  
  17.     function login() {  
  18.        //登陆  
  19.        var username = $("#txtUsername").val();  
  20.        var password = $("#txtPassword").val();  
  21.        var randCode = $("#txtRandCode").val();  
  22.        var rememberMeObj = document.getElementById("cbRememberMe");  
  23.        var rem = rememberMeObj.checked ? "1" : "";  
  24.   
  25.          
  26.        RSAUtils.setMaxDigits(200);  
  27.        //setMaxDigits(256);  
  28.        var key = new RSAUtils.getKeyPair("${publicKeyExponent}""""${publicKeyModulus}");  
  29.   
  30.        var encrypedPwd = RSAUtils.encryptedString(key,password);  
  31.        $.post("login.action", { username: username, password: encrypedPwd, randcode: randCode, rememberme: rem }, function (jsonData) {  
  32.            //请求完成  
  33.            //若是为true,证实该用户已经下载过,显示已下载提示,不然直接下载  
  34.            if (jsonData.success == true) {  
  35.                //登陆成功  
  36.                window.location.href = 'index.jsp';  
  37.            } else {  
  38.                //提示错误信息divErrors  
  39.                var ettText = "";  
  40.                if (username == "") {  
  41.                    ettText="用户名不能为空";  
  42.                }  
  43.                else if (password == "") {  
  44.                    ettText="密码不能为空";  
  45.                }  
  46.                else if (randCode == "") {  
  47.                    ettText="验证码不能为空";  
  48.                }  
  49.                else {  
  50.                    ettText=jsonData.msg;  
  51.                }  
  52.                alert(ettText);  
  53.            }  
  54.        });  
  55.     }</script>  
login.action

[java]  view plain  copy
  在CODE上查看代码片 派生到个人代码片
  1. RSAPrivateKey privateKey = (RSAPrivateKey)request.getSession().getAttribute("privateKey");  
  2. String descrypedPwd = RSAUtils.decryptByPrivateKey(password, privateKey); //解密后的密码,password是提交过来的密码  


RSAUtils.java

[java]  view plain  copy
  在CODE上查看代码片 派生到个人代码片
  1. package com.myapp.util;  
  2. import java.math.BigInteger;    
  3. import java.security.KeyFactory;    
  4. import java.security.KeyPair;    
  5. import java.security.KeyPairGenerator;    
  6. import java.security.NoSuchAlgorithmException;    
  7. import java.security.interfaces.RSAPrivateKey;    
  8. import java.security.interfaces.RSAPublicKey;    
  9. import java.security.spec.RSAPrivateKeySpec;    
  10. import java.security.spec.RSAPublicKeySpec;    
  11. import java.util.HashMap;   
  12. import javax.crypto.Cipher;   
  13.   
  14. public class RSAUtils {  
  15.     /**  
  16.      * 生成公钥和私钥  
  17.      * @throws NoSuchAlgorithmException   
  18.      *  
  19.      */    
  20.     public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException{    
  21.         HashMap<String, Object> map = new HashMap<String, Object>();    
  22.         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"new org.bouncycastle.jce.provider.BouncyCastleProvider());    
  23.         keyPairGen.initialize(1024);    
  24.         KeyPair keyPair = keyPairGen.generateKeyPair();    
  25.         RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();    
  26.         RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();    
  27.         map.put("public", publicKey);    
  28.         map.put("private", privateKey);    
  29.         return map;    
  30.     }    
  31.     /**  
  32.      * 使用模和指数生成RSA公钥  
  33.      *   
  34.      *   
  35.      * @param modulus  
  36.      *            模  
  37.      * @param exponent  
  38.      *            指数  
  39.      * @return  
  40.      */    
  41.     public static RSAPublicKey getPublicKey(String modulus, String exponent) {    
  42.         try {    
  43.             BigInteger b1 = new BigInteger(modulus);    
  44.             BigInteger b2 = new BigInteger(exponent);    
  45.             KeyFactory keyFactory = KeyFactory.getInstance("RSA"new org.bouncycastle.jce.provider.BouncyCastleProvider());    
  46.             RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);    
  47.             return (RSAPublicKey) keyFactory.generatePublic(keySpec);    
  48.         } catch (Exception e) {    
  49.             e.printStackTrace();    
  50.             return null;    
  51.         }    
  52.     }    
  53.     
  54.     /**  
  55.      * 使用模和指数生成RSA私钥  
  56.       
  57.      * /None/NoPadding】  
  58.      *   
  59.      * @param modulus  
  60.      *            模  
  61.      * @param exponent  
  62.      *            指数  
  63.      * @return  
  64.      */    
  65.     public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {    
  66.         try {    
  67.             BigInteger b1 = new BigInteger(modulus);    
  68.             BigInteger b2 = new BigInteger(exponent);    
  69.             KeyFactory keyFactory = KeyFactory.getInstance("RSA"new org.bouncycastle.jce.provider.BouncyCastleProvider());    
  70.             RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);    
  71.             return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);    
  72.         } catch (Exception e) {    
  73.             e.printStackTrace();    
  74.             return null;    
  75.         }    
  76.     }    
  77.     
  78.     /**  
  79.      * 公钥加密  
  80.      *   
  81.      * @param data  
  82.      * @param publicKey  
  83.      * @return  
  84.      * @throws Exception  
  85.      */    
  86.     public static String encryptByPublicKey(String data, RSAPublicKey publicKey)    
  87.             throws Exception {    
  88.         Cipher cipher = Cipher.getInstance("RSA"new org.bouncycastle.jce.provider.BouncyCastleProvider());    
  89.         cipher.init(Cipher.ENCRYPT_MODE, publicKey);    
  90.         // 模长    
  91.         int key_len = publicKey.getModulus().bitLength() / 8;    
  92.         // 加密数据长度 <= 模长-11    
  93.         String[] datas = splitString(data, key_len - 11);    
  94.         String mi = "";    
  95.         //若是明文长度大于模长-11则要分组加密    
  96.         for (String s : datas) {    
  97.             mi += bcd2Str(cipher.doFinal(s.getBytes()));    
  98.         }    
  99.         return mi;    
  100.     }    
  101.     
  102.     /**  
  103.      * 私钥解密  
  104.      *   
  105.      * @param data  
  106.      * @param privateKey  
  107.      * @return  
  108.      * @throws Exception  
  109.      */    
  110.     public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey)    
  111.             throws Exception {    
  112.         Cipher cipher = Cipher.getInstance("RSA"new org.bouncycastle.jce.provider.BouncyCastleProvider());    
  113.         cipher.init(Cipher.DECRYPT_MODE, privateKey);    
  114.         //模长    
  115.         int key_len = privateKey.getModulus().bitLength() / 8;    
  116.         byte[] bytes = data.getBytes();    
  117.         byte[] bcd = ASCII_To_BCD(bytes, bytes.length);    
  118.         //System.err.println(bcd.length);    
  119.         //若是密文长度大于模长则要分组解密    
  120.         String ming = "";    
  121.         byte[][] arrays = splitArray(bcd, key_len);    
  122.         for(byte[] arr : arrays){    
  123.             ming += new String(cipher.doFinal(arr));    
  124.         }    
  125.         return ming;    
  126.     }    
  127.     /**  
  128.      * ASCII码转BCD码  
  129.      *   
  130.      */    
  131.     public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {    
  132.         byte[] bcd = new byte[asc_len / 2];    
  133.         int j = 0;    
  134.         for (int i = 0; i < (asc_len + 1) / 2; i++) {    
  135.             bcd[i] = asc_to_bcd(ascii[j++]);    
  136.             bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));    
  137.         }    
  138.         return bcd;    
  139.     }    
  140.     public static byte asc_to_bcd(byte asc) {    
  141.         byte bcd;    
  142.     
  143.         if ((asc >= '0') && (asc <= '9'))    
  144.             bcd = (byte) (asc - '0');    
  145.         else if ((asc >= 'A') && (asc <= 'F'))    
  146.             bcd = (byte) (asc - 'A' + 10);    
  147.         else if ((asc >= 'a') && (asc <= 'f'))    
  148.             bcd = (byte) (asc - 'a' + 10);    
  149.         else    
  150.             bcd = (byte) (asc - 48);    
  151.         return bcd;    
  152.     }    
  153.     /**  
  154.      * BCD转字符串  
  155.      */    
  156.     public static String bcd2Str(byte[] bytes) {    
  157.         char temp[] = new char[bytes.length * 2], val;    
  158.     
  159.         for (int i = 0; i < bytes.length; i++) {    
  160.             val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);    
  161.             temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');    
  162.     
  163.             val = (char) (bytes[i] & 0x0f);    
  164.             temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');    
  165.         }    
  166.         return new String(temp);    
  167.     }    
  168.     /**  
  169.      * 拆分字符串  
  170.      */    
  171.     public static String[] splitString(String string, int len) {    
  172.         int x = string.length() / len;    
  173.         int y = string.length() % len;    
  174.         int z = 0;    
  175.         if (y != 0) {    
  176.             z = 1;    
  177.         }    
  178.         String[] strings = new String[x + z];    
  179.         String str = "";    
  180.         for (int i=0; i<x+z; i++) {    
  181.             if (i==x+z-1 && y!=0) {    
  182.                 str = string.substring(i*len, i*len+y);    
  183.             }else{    
  184.                 str = string.substring(i*len, i*len+len);    
  185.             }    
  186.             strings[i] = str;    
  187.         }    
  188.         return strings;    
  189.     }    
  190.     /**  
  191.      *拆分数组   
  192.      */    
  193.     public static byte[][] splitArray(byte[] data,int len){    
  194.         int x = data.length / len;    
  195.         int y = data.length % len;    
  196.         int z = 0;    
  197.         if(y!=0){    
  198.             z = 1;    
  199.         }    
  200.         byte[][] arrays = new byte[x+z][];    
  201.         byte[] arr;    
  202.         for(int i=0; i<x+z; i++){    
  203.             arr = new byte[len];    
  204.             if(i==x+z-1 && y!=0){    
  205.                 System.arraycopy(data, i*len, arr, 0, y);    
  206.             }else{    
  207.                 System.arraycopy(data, i*len, arr, 0, len);    
  208.             }    
  209.             arrays[i] = arr;    
  210.         }    
  211.         return arrays;    
  212.     }  
  213.     public static void main(String[] args) throws Exception{  
  214.         HashMap<String, Object> map = getKeys();    
  215.         //生成公钥和私钥    
  216.         RSAPublicKey publicKey = (RSAPublicKey) map.get("public");    
  217.         RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");    
  218.             
  219.         //模    
  220.         String modulus = publicKey.getModulus().toString();    
  221.         System.out.println("pubkey modulus="+modulus);  
  222.         //公钥指数    
  223.         String public_exponent = publicKey.getPublicExponent().toString();  
  224.         System.out.println("pubkey exponent="+public_exponent);  
  225.         //私钥指数    
  226.         String private_exponent = privateKey.getPrivateExponent().toString();    
  227.         System.out.println("private exponent="+private_exponent);  
  228.         //明文    
  229.         String ming = "111";    
  230.         //使用模和指数生成公钥和私钥    
  231.         RSAPublicKey pubKey = RSAUtils.getPublicKey(modulus, public_exponent);    
  232.         RSAPrivateKey priKey = RSAUtils.getPrivateKey(modulus, private_exponent);    
  233.         //加密后的密文    
  234.         String mi = RSAUtils.encryptByPublicKey(ming, pubKey);    
  235.         System.err.println("mi="+mi);    
  236.         //解密后的明文    
  237.         String ming2 = RSAUtils.decryptByPrivateKey(mi, priKey);    
  238.         System.err.println("ming2="+ming2);    
  239.     }  
  240. }  

---------------------------------------------------------------------------------------------------------------------------------------- 

若是您认为本教程质量不错,读后以为收获很大,预期工资能蹭蹭蹭的往上涨,那么不妨小额赞助我一下,让我有动力继续写出高质量的教程。 
   ----------------------------------------------------------------------------------------------------------------------------------------                                                           


最后,那个js的RSA实现我是在以下连接下载的:

http://www.oschina.net/code/snippet_1611_4789