有些对安全要求比较高的应用,需要和服务器做MD5的校验,这里提供Android获取本应用的MD5值的方法
/**
* 获取应用MD5
* @author YOLANDA
* @param context
* @return
*/
public static String getAPKMD5(Context context) {
String md5 = "";
String path = context.getApplicationContext().getPackageResourcePath();
File file = new File(path);
try {
md5 = StringUtil.getFileMD5String(file);
} catch (Exception e) {
e.printStackTrace();
}
return md5;
}
/**
* 获取文件MD5
* @author YOLANDA
* @param file
* @return
* @throws Exception
*/
public static String getFileMD5String(File file) throws Exception {
InputStream fis;
MessageDigest messagedigest = MessageDigest.getInstance("MD5");
fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int numRead = 0;
while ((numRead = fis.read(buffer)) > 0) {
messagedigest.update(buffer, 0, numRead);
}
fis.close();
return byte2Hex(messagedigest.digest());
}
/**
* byte[]转Hex字符串
* @author YOLANDA
* @param b
* @return
*/
public static String byte2Hex(byte[] b) {
if (null == b)
return null;
StringBuffer sBuffer = new StringBuffer();
String sTmep;
for (int i = 0; i < b.length; i++) {
sTmep = Integer.toHexString(b[i] & 0xFF);
if (sTmep.length() == 1)
sBuffer.append("0");
sBuffer.append(sTmep.toUpperCase(Locale.getDefault()));
}
return sBuffer.toString();
}String转hex 16进制,hex 16进制转String可以去看我另一片博文:
http://www.javashuo.com/article/p-mubbbdaz-vd.html