java实现MD5加密

package com.pingan.tools;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密
 */
public class MD5 {
	/**
	 * 获取MD5加密的字符串
	 * @param source 待加密的字符串
	 * @return 加密后的字符串
	 */
	public static final String encodeWithMD5(String source) {
		String result = "";
		
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byteToString(md.digest(source.getBytes("UTf-8")));
			System.out.println(result);
		} catch (NoSuchAlgorithmException e) {
			System.out.println("没有该加密算法," + e.getMessage());
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			System.out.println(source + ",包含不支持的字符编码," + e.getMessage());
			e.printStackTrace();
		}
		
		return result;
	}
	
	/**
	 * byte 转换成 String
	 * @param bytes 待转换的byte数组
	 * @return 转换成功的字符串
	 */
	private static String byteToString(byte[] bytes) {
		StringBuffer result = new StringBuffer("");
		if (null == bytes) {
			return result.toString();
		}
		
		for (int index = 0; index < bytes.length; index++) {
			int val = (int)bytes[index] & 0xff;
			if (val < 16) {
				result.append("0");
			}
			result.append(Integer.toHexString(val));
		}
		
		return result.toString().toUpperCase();
	}
	
}

你可能感兴趣的:(java实现MD5加密)