java MD5加密码

/**
 * 
 */
package com.wuhongbo.common.util.encry;

import java.security.MessageDigest;

/**
 * MD5加密
 * 
 * @author wuhongbo
 */
public class MD5Util
{
	private final static char hexDigits[] = { '0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

	/**
	 * MD5加密
	 * 
	 * @param s
	 *            加密内容
	 * @param hex
	 *            字符长度必须为16位,允许为空或长度为0
	 * @return
	 * @throws Exception
	 */
	public static String encode(String s, char[] hex) throws Exception
	{
		if (hex == null || hex.length == 0)
		{
			hex = hexDigits;
		}
		else if (hex.length != 16)
		{
			throw new Exception("掩码长度必须是16位的字符串");
		}

		try
		{
			byte[] strTemp = s.getBytes();
			MessageDigest mdTemp;
			mdTemp = MessageDigest.getInstance("MD5");

			byte[] md = mdTemp.digest(strTemp);

			// 处理掩码
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < md.length; i++)
			{
				int num = md[i];

//				String temp = Integer.toHexString(num & 0xFF);
//				if (temp.length() == 1)
//				{
//					temp = "0" + temp;
//				}	
//				sb.append(temp.toUpperCase());
				
				int n = num;
				if (n < 0)
				{
					n += 256;
				}
				int d1 = n / 16;
				int d2 = n % 16;

				String temp =hexDigits[d1] + "" + hexDigits[d2];
				sb.append(temp);
			}

			// 掩码处理

			return sb.toString().toUpperCase();
		}
		catch (Exception e)
		{
			throw new Exception("加密失败,请检查加密码算法。");
		}
	}

	/**
	 * MD5加密
	 * 
	 * @param s
	 *            加密内容
	 * @param hex
	 *            掩码,字符长度必须为16位,允许为空或长度为0
	 * @return
	 * @throws Exception
	 */
	public static String encode(String s, String hexStr) throws Exception
	{
		if (hexStr == null)
		{
			hexStr = "";
		}

		return encode(s, hexStr.toCharArray());
	}

	/**
	 * MD5加密
	 * 
	 * @param s
	 *            加密内容
	 * @return
	 * @throws Exception
	 */
	public static String encode(String s) throws Exception
	{
		return encode(s, "");
	}

	// 测试主函数
	public static void main(String args[])
	{
		try
		{

			System.out.println("MD5后:" + encode("admin"));

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值