以前一直没关注过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
- var key = new RSAUtils.getKeyPair("${publicKeyExponent}", "", "${publicKeyModulus}");
-
- var reversedPwd = password.split("").reverse().join("");
- 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进制进行转换的。改完后应该是这样:
- String publicKeyExponent = publicKey.getPublicExponent().toString(16);
- String publicKeyModulus = publicKey.getModulus().toString(16);
- request.setAttribute("publicKeyExponent", publicKeyExponent);
- request.setAttribute("publicKeyModulus", publicKeyModulus);
问题二:有个什么Padding之类的异常,是RSA算法中前面补齐的问题,缘由时js和java默认的RSA算法不一致。
通过分析,用RSA其余的provider能够解决此问题,因而在生成密码对的代码中,使用了
- 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文件中添加了以下代码:
- 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,内容以下:
- <?xml version="1.0" encoding="UTF-8"?>
- <module xmlns="urn:jboss:module:1.1" name="org.bouncycastle">
- <resources>
- <resource-root path="bcprov-jdk16-1.46.jar"/>
- </resources>
- <dependencies>
- <module name="javax.api" slot="main" export="true"/>
- </dependencies>
- </module>
还须要在web应用的META-INF\MANIFEST.MF中加入Dependencies: org.bouncycastle
我是maven工程,须要配置pom:
- <plugin>
- <artifactId>maven-war-plugin</artifactId>
- <version>${version.war.plugin}</version>
- <configuration>
-
- <failOnMissingWebXml>true</failOnMissingWebXml>
- <version>3.0</version>
- <archive>
- <manifestEntries>
- <Dependencies>org.bouncycastle</Dependencies>
- </manifestEntries>
- </archive>
- </configuration>
-
- </plugin>
主要是archive节点的配置,这样打包后MANIFEST.MF的内容就会变了
不能传附件可咋整呢?贴代码吧:
login.jsp
- <script src="js/lib/security.js" type="text/javascript"></script>
- <script type="text/javascript">
- <%
- HashMap<String, Object> map = RSAUtils.getKeys();
-
- RSAPublicKey publicKey = (RSAPublicKey) map.get("public");
- RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");
-
- session.setAttribute("privateKey", privateKey);
-
-
- String publicKeyExponent = publicKey.getPublicExponent().toString(16);
- String publicKeyModulus = publicKey.getModulus().toString(16);
- request.setAttribute("publicKeyExponent", publicKeyExponent);
- request.setAttribute("publicKeyModulus", publicKeyModulus);
- %>
- function login() {
-
- var username = $("#txtUsername").val();
- var password = $("#txtPassword").val();
- var randCode = $("#txtRandCode").val();
- var rememberMeObj = document.getElementById("cbRememberMe");
- var rem = rememberMeObj.checked ? "1" : "";
-
-
- RSAUtils.setMaxDigits(200);
-
- var key = new RSAUtils.getKeyPair("${publicKeyExponent}", "", "${publicKeyModulus}");
-
- var encrypedPwd = RSAUtils.encryptedString(key,password);
- $.post("login.action", { username: username, password: encrypedPwd, randcode: randCode, rememberme: rem }, function (jsonData) {
-
-
- if (jsonData.success == true) {
-
- window.location.href = 'index.jsp';
- } else {
-
- var ettText = "";
- if (username == "") {
- ettText="用户名不能为空";
- }
- else if (password == "") {
- ettText="密码不能为空";
- }
- else if (randCode == "") {
- ettText="验证码不能为空";
- }
- else {
- ettText=jsonData.msg;
- }
- alert(ettText);
- }
- });
- }</script>
login.action
- RSAPrivateKey privateKey = (RSAPrivateKey)request.getSession().getAttribute("privateKey");
- String descrypedPwd = RSAUtils.decryptByPrivateKey(password, privateKey);
RSAUtils.java
- package com.myapp.util;
- import java.math.BigInteger;
- import java.security.KeyFactory;
- import java.security.KeyPair;
- import java.security.KeyPairGenerator;
- import java.security.NoSuchAlgorithmException;
- import java.security.interfaces.RSAPrivateKey;
- import java.security.interfaces.RSAPublicKey;
- import java.security.spec.RSAPrivateKeySpec;
- import java.security.spec.RSAPublicKeySpec;
- import java.util.HashMap;
- import javax.crypto.Cipher;
-
- public class RSAUtils {
-
-
-
-
-
- public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException{
- HashMap<String, Object> map = new HashMap<String, Object>();
- KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
- keyPairGen.initialize(1024);
- KeyPair keyPair = keyPairGen.generateKeyPair();
- RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
- RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
- map.put("public", publicKey);
- map.put("private", privateKey);
- return map;
- }
-
-
-
-
-
-
-
-
-
-
- public static RSAPublicKey getPublicKey(String modulus, String exponent) {
- try {
- BigInteger b1 = new BigInteger(modulus);
- BigInteger b2 = new BigInteger(exponent);
- KeyFactory keyFactory = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
- RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
- return (RSAPublicKey) keyFactory.generatePublic(keySpec);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
-
-
-
-
-
-
-
-
-
-
-
-
- public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
- try {
- BigInteger b1 = new BigInteger(modulus);
- BigInteger b2 = new BigInteger(exponent);
- KeyFactory keyFactory = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
- RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
- return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
-
-
-
-
-
-
-
-
-
- public static String encryptByPublicKey(String data, RSAPublicKey publicKey)
- throws Exception {
- Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
- cipher.init(Cipher.ENCRYPT_MODE, publicKey);
-
- int key_len = publicKey.getModulus().bitLength() / 8;
-
- String[] datas = splitString(data, key_len - 11);
- String mi = "";
-
- for (String s : datas) {
- mi += bcd2Str(cipher.doFinal(s.getBytes()));
- }
- return mi;
- }
-
-
-
-
-
-
-
-
-
- public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey)
- throws Exception {
- Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
- cipher.init(Cipher.DECRYPT_MODE, privateKey);
-
- int key_len = privateKey.getModulus().bitLength() / 8;
- byte[] bytes = data.getBytes();
- byte[] bcd = ASCII_To_BCD(bytes, bytes.length);
-
-
- String ming = "";
- byte[][] arrays = splitArray(bcd, key_len);
- for(byte[] arr : arrays){
- ming += new String(cipher.doFinal(arr));
- }
- return ming;
- }
-
-
-
-
- public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {
- byte[] bcd = new byte[asc_len / 2];
- int j = 0;
- for (int i = 0; i < (asc_len + 1) / 2; i++) {
- bcd[i] = asc_to_bcd(ascii[j++]);
- bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));
- }
- return bcd;
- }
- public static byte asc_to_bcd(byte asc) {
- byte bcd;
-
- if ((asc >= '0') && (asc <= '9'))
- bcd = (byte) (asc - '0');
- else if ((asc >= 'A') && (asc <= 'F'))
- bcd = (byte) (asc - 'A' + 10);
- else if ((asc >= 'a') && (asc <= 'f'))
- bcd = (byte) (asc - 'a' + 10);
- else
- bcd = (byte) (asc - 48);
- return bcd;
- }
-
-
-
- public static String bcd2Str(byte[] bytes) {
- char temp[] = new char[bytes.length * 2], val;
-
- for (int i = 0; i < bytes.length; i++) {
- val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);
- temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
-
- val = (char) (bytes[i] & 0x0f);
- temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
- }
- return new String(temp);
- }
-
-
-
- public static String[] splitString(String string, int len) {
- int x = string.length() / len;
- int y = string.length() % len;
- int z = 0;
- if (y != 0) {
- z = 1;
- }
- String[] strings = new String[x + z];
- String str = "";
- for (int i=0; i<x+z; i++) {
- if (i==x+z-1 && y!=0) {
- str = string.substring(i*len, i*len+y);
- }else{
- str = string.substring(i*len, i*len+len);
- }
- strings[i] = str;
- }
- return strings;
- }
-
-
-
- public static byte[][] splitArray(byte[] data,int len){
- int x = data.length / len;
- int y = data.length % len;
- int z = 0;
- if(y!=0){
- z = 1;
- }
- byte[][] arrays = new byte[x+z][];
- byte[] arr;
- for(int i=0; i<x+z; i++){
- arr = new byte[len];
- if(i==x+z-1 && y!=0){
- System.arraycopy(data, i*len, arr, 0, y);
- }else{
- System.arraycopy(data, i*len, arr, 0, len);
- }
- arrays[i] = arr;
- }
- return arrays;
- }
- public static void main(String[] args) throws Exception{
- HashMap<String, Object> map = getKeys();
-
- RSAPublicKey publicKey = (RSAPublicKey) map.get("public");
- RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");
-
-
- String modulus = publicKey.getModulus().toString();
- System.out.println("pubkey modulus="+modulus);
-
- String public_exponent = publicKey.getPublicExponent().toString();
- System.out.println("pubkey exponent="+public_exponent);
-
- String private_exponent = privateKey.getPrivateExponent().toString();
- System.out.println("private exponent="+private_exponent);
-
- String ming = "111";
-
- RSAPublicKey pubKey = RSAUtils.getPublicKey(modulus, public_exponent);
- RSAPrivateKey priKey = RSAUtils.getPrivateKey(modulus, private_exponent);
-
- String mi = RSAUtils.encryptByPublicKey(ming, pubKey);
- System.err.println("mi="+mi);
-
- String ming2 = RSAUtils.decryptByPrivateKey(mi, priKey);
- System.err.println("ming2="+ming2);
- }
- }
----------------------------------------------------------------------------------------------------------------------------------------
若是您认为本教程质量不错,读后以为收获很大,预期工资能蹭蹭蹭的往上涨,那么不妨小额赞助我一下,让我有动力继续写出高质量的教程。
----------------------------------------------------------------------------------------------------------------------------------------
最后,那个js的RSA实现我是在以下连接下载的:
http://www.oschina.net/code/snippet_1611_4789