www.pudn.com > MD5.rar > NewStringMD5.java


package com.md5.chen; 
 
import org.apache.commons.codec.binary.Base64; 
 
import java.io.*; 
import java.security.DigestInputStream; 
import java.security.MessageDigest; 
 
//获取BASE64编码的字符串MD5 
public class NewStringMD5 
{ 
	public static byte[] encode(byte[] buf) 
	{ 
		if (buf == null) 
		{ 
			return encode(buf, 0, 0); 
		} else 
		{ 
			return encode(buf, 0, buf.length); 
		} 
	} 
 
	// 将 buf 进行 BASE64 编码 
	public static byte[] encode(byte[] buf, int pos, int length) 
	{ 
		byte[] result = null; 
 
		if (length > 0) 
		{ 
			if (pos == 0 && buf.length == length) 
			{ 
				return Base64.encodeBase64(buf); 
			} else 
			{ 
				byte[] newbuf = new byte[length]; 
				System.arraycopy(buf, pos, newbuf, 0, length); 
				result = Base64.encodeBase64(newbuf); 
			} 
		} 
		return result; 
	} 
 
	// 将 BASE64 编码的字符串 buf 进行解码 
	public static byte[] decode(byte[] buf, int pos, int length) 
			throws IOException 
	{ 
		byte[] result = null; 
 
		if (length > 0) 
		{ 
			result = FastBase64.decodeBase64(buf, pos, length); 
 
			// if (pos == 0 && buf.length == length) { 
			// result = Base64.decodeBase64(buf); 
			// } else { 
			// byte[] newbuf = new byte[length]; 
			// System.arraycopy(buf, pos, newbuf, 0, length); 
			// result = Base64.decodeBase64(newbuf); 
			// } 
		} 
 
		return result; 
	} 
	 
	public static void main(String[] args)throws Exception  
	{ 
		String t = "A"; 
		String  md5String = ""; 
		// 为一个字符串计算MD5 
		try 
		{ 
			// 生成MessageDigest对象MD 
			MessageDigest MD = MessageDigest.getInstance("MD5"); 
		    // 传入要计算的字符串 
			MD.update(t.getBytes("UTF-8")); 
			// 计算MD5 
			 md5String = new String(encode(MD.digest())); 
 
		} catch (Exception e) 
		{ 
			System.out.println(e.getMessage()); 
		} 
		System.out.println("字符串 "+t+" 的BASE64编码的MD5:" + md5String); 
        
		/* 
		String tt="QQ=="; 
		 
		byte[] decodeByte= decode(tt.getBytes(),0,tt.length()); 
		 
		System.out.println("length:"+decodeByte.length); 
		//String decodeString = new String(decode(tt.getBytes(),0,tt.length())); 
	   // System.out.println("解码后:"+decodeString); 
		for(int i=0;i