java生成字符串的MD5值

下面的代码实现了MD5值的生成:

public class MD5Test2 {
	public static void main(String[] args) {
		System.out.println(MD5Test2.MD5Operation("hello"));
		System.out.println(MD5Test2.getMD5("hello"));
	}
        //通过java.math包的BigInteger类实现十六进制的转换
	public final static String MD5Operation(String s){
		try {
			byte strTemp[] = s.getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(strTemp);
			byte b[] = md.digest();
			
			BigInteger bigInt = new BigInteger(1, b);
			return bigInt.toString(16);
			
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}
        //利用java底层代码实现十六进制的转换
	public final static String getMD5(String s) {
		char hexDigits[] = {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
		try {
			byte strTemp[] = s.getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(strTemp);
			byte b[] = md.digest();
			
			int len = b.length;
			char str[] = new char[len*2];
			int k=0;
			for(int i=0; i<len; i++){
				str[k++] = hexDigits[b[i] >>> 4 & 0xf];
				str[k++] = hexDigits[b[i] & 0xf];
			}
			return new String(str);
			
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}
}
posted @ 2014-07-15 08:45  小样儿1020  阅读(2393)  评论(0编辑  收藏  举报