JavaWeb兑现服务器端到客户端的验证码(MD5)校验

JavaWeb实现服务器端到客户端的验证码(MD5)校验

1. 首先看看服务端产生验证码的代码。(很简单 A-Z, 然后是0-9)

/**
 * 产生验证码类(MD5)加密
 * @author Thunder
 *
 */
public class VerificationCode {

	/**
	 * 产生指定位数的验证码
	 * @param codeLength 指定验证码的长度
	 * @return 随机生成的验证码
	 */
	public static String getCode(int codeLength) {
		
		StringBuffer stringBuffer = new StringBuffer();
		
		char[] selectChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
				'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T',
				'U', 'V', 'W', 'X', 'Y', 'Z'};

		for ( int i = 0; i < codeLength; i++) {
			int charIndex = (int) Math.floor(Math.random() * selectChar.length);
			stringBuffer.append(selectChar[charIndex]);
		}
		
		return stringBuffer.toString();
	}
	
}

(注:上述已经打包成jar包) 

 

 

2. 服务端页面(用户浏览器)在加载的时候, 异步调用 服务器端的代码。

返回随机生成的验证码, 并加载到页面上。

关于异步调用, Ajax , 可以直接用JQuery的Ajax库来做, 直接请求Http。

也可以用DWR框架来做, 直接访问一个类的一个方法。 本文用的是DWR。

有关于DWR如何使用, 在这里就废话不多说, 入门菜鸟可以先学学。

 

<script type="text/javascript">
		function addVerifiCode() {
			VerificationCode.getCode(4, function(serverReturnString) {
				$("#checkCode").val(serverReturnString);
			});
		}
	</script>

 DWR JS文件的导入:

<script type='text/javascript' src='/CSMS/dwr/engine.js'></script>
  	<script type='text/javascript' src='/CSMS/dwr/interface/VerificationCode.js'></script>
  	<script type='text/javascript' src='/CSMS/dwr/util.js'></script>
 

然后是显示验证码的框框:

<input type="text" id="checkCode" class="checkCode" style="width: 55px" readonly="readonly" onclick="addVerifiCode();"/>

 并且在body onload的时候调用:

<body onload="addVerifiCode();">

 


3. DWR访问的Java类如下:

/**
	 * 生成验证码
	 * @param codeLength
	 * @param session
	 * @return
	 */
	public static String getCode(int codeLength, HttpSession session) {
		String veriCode = com.thunder.VerificationCode.getCode(codeLength);
		try {
			veriCode = veriCode.toUpperCase();
			session.setAttribute(Public.SESSION_LOGIN_CHECK_CODE, MD5Util.getEncryptedPwd(veriCode));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
		return veriCode;
	}

 主要是将生成的验证码, 经过MD5散列后放到Session里面去。


后面将会贴出关于MD5 散列加密的源码。


4. 用户, 即客户端提交表单验证码, 进行验证的过程, 代码:

MD5Util.validPassword(checkCode, (String) session.get(Public.SESSION_LOGIN_CHECK_CODE)

 说明一下: checkCode是前台提交的验证码, 后面的另一个参数是刚才第三步生成的验证码MD5散列后的字符串。

前后2个进行散列比较, 返回值是true, 则证明验证码输入正确, 否则, 反之。

 

 

5. 最后, 贴上MD5的散列, 及其比较。

/**
 * MD5 散列码 工具包
 * 
 * @author Thunder
 * 
 */
public class MD5Util {

	private static final String HEX_NUMS_STR = "0123456789ABCDEF";
	private static final Integer SALT_LENGTH = 12;

	public static byte[] hexStringToByte(String hex) {
		int len = (hex.length() / 2);
		byte[] result = new byte[len];
		char[] hexChars = hex.toCharArray();
		for (int i = 0; i < len; i++) {
			int pos = i * 2;
			result[i] = (byte) (HEX_NUMS_STR.indexOf(hexChars[pos]) << 4 | HEX_NUMS_STR
					.indexOf(hexChars[pos + 1]));
		}
		return result;
	}

	public static String byteToHexString(byte[] b) {
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			hexString.append(hex.toUpperCase());
		}
		return hexString.toString();
	}

	/**
	 * 校验密码
	 * @param password
	 * @param passwordInDb
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	public static boolean validPassword(String password, String passwordInDb)
			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		// 将16进制字符串格式口令转换成字节数组
		byte[] pwdInDb = hexStringToByte(passwordInDb);
		// 声明盐变量
		byte[] salt = new byte[SALT_LENGTH];
		// 将盐从数据库中保存的口令字节数组中提取出来
		System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH);
		// 创建消息摘要对象
		MessageDigest md = MessageDigest.getInstance("MD5");
		// 将盐数据传入消息摘要对象
		md.update(salt);
		// 将口令的数据传给消息摘要对象
		md.update(password.getBytes("UTF-8"));
		// 生成输入口令的消息摘要
		byte[] digest = md.digest();
		// 声明一个保存数据库中口令消息摘要的变量
		byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH];
		// 取得数据库中口令的消息摘要
		System
				.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0,
						digestInDb.length);
		// 比较根据输入口令生成的消息摘要和数据库中消息摘要是否相同
		if (Arrays.equals(digest, digestInDb)) {
			// 口令正确返回口令匹配消息
			return true;
		} else {
			// 口令不正确返回口令不匹配消息
			return false;
		}
	}
	
	/**
	 * 进行MD5 编码
	 * @param password
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	public static String getEncryptedPwd(String password)
			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		// 声明加密后的口令数组变量
		byte[] pwd = null;
		// 随机数生成器
		SecureRandom random = new SecureRandom();
		// 声明盐数组变量
		byte[] salt = new byte[SALT_LENGTH];
		// 将随机数放入盐变量中
		random.nextBytes(salt);

		// 声明消息摘要对象
		MessageDigest md = null;
		// 创建消息摘要
		md = MessageDigest.getInstance("MD5");
		// 将盐数据传入消息摘要对象
		md.update(salt);
		// 将口令的数据传给消息摘要对象
		md.update(password.getBytes("UTF-8"));
		// 获得消息摘要的字节数组
		byte[] digest = md.digest();

		// 因为要在口令的字节数组中存放盐,所以加上盐的字节长度
		pwd = new byte[digest.length + SALT_LENGTH];
		// 将盐的字节拷贝到生成的加密口令字节数组的前12个字节,以便在验证口令时取出盐
		System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH);
		// 将消息摘要拷贝到加密口令字节数组从第13个字节开始的字节
		System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length);
		// 将字节数组格式加密后的口令转化为16进制字符串格式的口令
		return byteToHexString(pwd);
	}

}

 


本文实属原创, 转载请说明~谢谢。