基本过程如下:
1)把要加密的字符串转换成字节数组
2)获取MessageDigest对象,利用该对象digest方法完成加密,返回字节数组
3)将字节数组利用base64算法转换成等长字符串
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import sun.misc.BASE64Encoder;
public class MD5_Test {
public static void main(String args[]){
System.out.println(MD5("abc"));
}
public static String MD5(String oldStr){
byte[] oldBytes=oldStr.getBytes();
MessageDigest md;
try{
md=MessageDigest.getInstance("MD5");
byte[] newBytes=md.digest(oldBytes);
BASE64Encoder encoder=new BASE64Encoder();
String newStr=encoder.encode(newBytes);
return newStr;
}catch(NoSuchAlgorithmException e){
return null;
}
}
}