项目实践——MD5加密

来源:互联网 发布:知乎 财务进销存一体 编辑:程序博客网 时间:2024/05/18 00:41

  在项目中,需要用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@Overridepublic 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加密过的,将用户登录的密码亦经过MD5加密,匹配成功即可登录





0 0
原创粉丝点击