public static String MD5(String code) {
StringBuilder builder = new StringBuilder();
try {
byte[] bytes = code.getBytes();
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(bytes);
byte[] md5 = digest.digest();
for (int i = 0; i < md5.length; i++) {
String str = Integer.toHexString(md5[i] & 0xff);
if (str.length() == 1) {
builder.append("0") ;
}
builder.append(str);
}
return builder.toString();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// 计算一个文件的MD5
public static String md5 (File file ){
StringBuilder builder =new StringBuilder() ;
try {
MessageDigest digest =MessageDigest.getInstance("MD5");
FileInputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[2048] ;
int len = 0 ;
while ((len =inputStream.read(buffer))!=-1){
digest.update(buffer,0,len);
}
byte[] md5 = digest.digest() ;
for(int i=0 ;i<md5.length;i++){
String str = Integer.toHexString(0xff&md5[i]);
if(str.length()==1){
builder.append("0");
}
builder.append(str);
}
inputStream.close() ;
}
return builder.toString() ;
}