码迷,mamicode.com
首页 > 其他好文 > 详细

项目实践——MD5加密

时间:2015-04-30 18:08:23      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

  在项目中,需要用MD5进行加密,这里分享一个MD5加密类。

MD5加密类:



public class Md5 {
	private static String DEFAULT_JCE = "com.sun.crypto.provider.SunJCE";
    private static String IBM_JCE = "com.ibm.crypto.provider.IBMJCE";
    protected static final Log log = LogFactory.getLog(Md5.class);
    
    /**
     * 初始化系统加密算法提供者
     */
    static
    {
        
        try
        {
            Security.addProvider((Provider)Class.forName(DEFAULT_JCE).newInstance());
        }
        catch (Exception e)
        {
            log.info(e);
            try
            {
                Security.addProvider((Provider)Class.forName(IBM_JCE).newInstance());
            }
            catch (Exception ex)
            {
                log.info(ex);
            }
        }
    }
    
    
    /**
     * get hex string
     * 
     * @param x
     * @return
     */
    private static String hexDigit(byte x)
    {
        StringBuffer sb = new StringBuffer();
        char c;
        // First nibble
        c = (char) ((x >> 4) & 0xf);
        if (c > 9)
        {
            c = (char) ((c - 10) + 'a');
        }
        else
        {
            c = (char) (c + '0');
        }
        sb.append(c);
        // Second nibble
        c = (char) (x & 0xf);
        if (c > 9)
        {
            c = (char) ((c - 10) + 'a');
        }
        else
        {
            c = (char) (c + '0');
        }
        sb.append(c);
        return sb.toString();
    }

    /**
     * 加密
     * 
     * @param content
     *            加密内容
     * @return 加密串
     */
    public static String encrypt(String content)
    {
        try
        {
            MessageDigest algorithm = null;
            algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            if (content != null)
            {
                algorithm.reset();
                algorithm.update(content.getBytes());
                byte digest[] = algorithm.digest();
                StringBuffer hexString = new StringBuffer();
                int digestLength = digest.length;
                for (int i = 0; i < digestLength; i++)
                {
                    hexString.append(hexDigit(digest[i]));

                }
                return hexString.toString();
            }
            else
            {
                return "";
            }
        }
        catch (NoSuchAlgorithmException ex)
        {
            //加密过程中出现异常,采用原始的的内容串
            return content;
        }
    }
   
    

}



运行测试:



    @Test
    public void testMd5(){
    	
    	System.err.println(this.encrypt("123456"));
    }
    


结果:

e10adc3949ba59abbe56e057f20f883e



用户登录:


	@RequestMapping("/login.do")
	@ResponseBody
	@Override
	public Object login(HttpServletRequest request, HttpServletResponse response) {
		Logger log = Logger.getLogger(getClass());
		String biskeep = "";
		Md5 md5=new Md5();
		try {
			String loginName = request.getParameter("loginName");
			String loginPassword = md5.encrypt(request.getParameter("loginPassword"));
			HttpSession session = request.getSession();
			if (loginName != null && !loginName.trim().equals("")
					&& loginPassword != null
					&& !loginPassword.trim().equals("")) {
				SysUser user = userService.queryUser(loginName, loginPassword);

				biskeep = user.getBiskeep();
				
				// 查询该用户的部门信息
				String deptIdStr = user.getDepartmentid();
				SysDept sysDept=deptService.queryEntityById(SysDept.class, deptIdStr);
				
				// SysDept sysDept=null;
				// 查询该用户的角色信息,应该是一个list集合
				String roleIdStr = roleService.getRoleIdStr(user.getId());
				session.setAttribute(ConstValues.LOGIN_DEPT_ID, deptIdStr);
				session.setAttribute(ConstValues.LOGIN_ROLE_ID, roleIdStr);
				session.setAttribute(ConstValues.LOGIN_DEPT_TYPE, sysDept.getCdeptno());
				session.setAttribute("depId", deptIdStr);
				// 将用户信息放入到session中去
				session.setAttribute(ConstValues.LOGIN_USER_NAME,user.getCloginname());
				session.setAttribute(ConstValues.LOGIN_USER_ID, user.getId());
				session.setAttribute(ConstValues.LOGIN_FIRSTNAME,user.getFirstname());
				session.setAttribute(ConstValues.LOGIN_LASTNAME,user.getLastname());
				session.setAttribute(ConstValues.LOGIN_USER_PASSWORD, user.getCpassword());

				String ip = request.getHeader("x-forwarded-for");
				if (ip == null || ip.length() == 0
						|| "unknown".equalsIgnoreCase(ip)) {
					ip = request.getHeader("Proxy-Client-IP");
				}
				if (ip == null || ip.length() == 0
						|| "unknown".equalsIgnoreCase(ip)) {
					ip = request.getHeader("WL-Proxy-Client-IP");
				}
				if (ip == null || ip.length() == 0
						|| "unknown".equalsIgnoreCase(ip)) {
					ip = request.getRemoteAddr();
				}
				log.info("本机ip:" + ip);
				session.setAttribute(ConstValues.LOGIN_IP, ip);
				Map<String, String> param = new HashMap<String, String>();
				param.put("ip", ip);
			}
			JSONObject obj = createSuccessMessage(null);
			obj.put("biskeep", biskeep);
			
			String depId = (String)  session.getAttribute(ConstValues.LOGIN_DEPT_ID);
			String ss  = (String) session.getAttribute(ConstValues.LOGIN_USER_ID);
			
			return obj.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return createErrorMessage(e.getMessage()).toString();
		}
	}








项目实践——MD5加密

标签:

原文地址:http://blog.csdn.net/zhangleilei4869/article/details/45397667

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