本人一见md5/sha/rsa等加密算法就头疼, 在app自动更新时, 需要对apk进行md5校验, 因此在网上弄了一段代码, 进过本人改写后, 如下. 但是不是很明白其中toHexString方法的意思. 因此求大神解释一下toHexString方法的含意, 以及分析整个类, 为何toHexString方法要这样写 ?
package com.example;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
public final class MD5Checksum {
private static final char HEX_DIGITS[] =
{
'0', '1', '2', '3', '4',
'5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f'
};
public static String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
sb.append(HEX_DIGITS[b[i] & 0x0f]);
}
return sb.toString();
}
public static String md5sum(String absoluteFilePath) {
InputStream inputStream = null;
ByteArrayOutputStream outputStream = null;
byte[] buffer = new byte[1024];
int readedLength;
MessageDigest md5;
try{
inputStream = new FileInputStream(absoluteFilePath);
outputStream = new ByteArrayOutputStream();
md5 = MessageDigest.getInstance("MD5");
while((readedLength = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, readedLength);
}
byte[] bytes = outputStream.toByteArray();
md5.update(bytes, 0, bytes.length);
return toHexString(md5.digest());
} catch (Exception e) {
System.out.println("get file \"" + absoluteFilePath+ "\" md5 failed !");
return null;
} finally {
try {
if(outputStream != null) outputStream.close();
if(inputStream != null) inputStream.close();
} catch (Exception e) {}
}
}
public static void main(String[] args) {
System.out.println(md5sum(new File("java-demo2/demo.json").getAbsolutePath()));
}
}