MD5加密与验证

package com.study;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Test {

	
	public static String encodeByMD5(String userPwd){
		
		String pwdByMd5 = "";
		
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			
			byte[] bytePwd = md5.digest(userPwd.getBytes());
			 
			StringBuffer hexValue = new StringBuffer();  
			
			 for (int i = 0; i < bytePwd.length; i++) {  
				 int val = ((int) bytePwd[i]) & 0xff;  
				 if (val < 16)  
					 hexValue.append("0");  
				 hexValue.append(Integer.toHexString(val));  
			 }  
			 pwdByMd5 = hexValue.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		
		
		return pwdByMd5;
	}
	
	
	 /** 
        * 验证输入的密码是否正确 
        * @param password    加密后的密码 
        * @param inputString    输入的字符串 
        * @return    验证结果,TRUE:正确 FALSE:错误 
		*/  
		public static boolean validatePassword(String password, String inputString){  
			if(password.equals(encodeByMD5(inputString))){  
		         return true;  
		    } else{  
		         return false;  
		    }  
	    }  

	
	
}

  与 0xff进行&运算 是为了用8字节的byte类型获取一个32字节的int类型数

posted @ 2015-08-06 10:25  凉城  阅读(1192)  评论(0编辑  收藏  举报