1. 說明
android自帶的MD5校驗類
2. 例程
1) 功能
對文件/init.rc做MD5計算,並以字串的方式顯示
2) 可從此處下載可獨立運行的代碼
http://download.csdn.Net/source/2660824
3) 使用Linux命令得到MD5值
$ md5sum init.rc
4) 核心代碼及說明
- import Java.security.MessageDigest;
- import Java.io.FileInputStream;
- import Java.io.InputStream;
- public class MD5 {
- private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
- 'A', 'B', 'C', 'D', 'E', 'F' };
- public static void main(String[] args)
- {
- System.out.println(md5sum("/init.rc"));
- }
- 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 filename) {
- InputStream fis;
- byte[] buffer = new byte[1024];
- int numRead = 0;
- MessageDigest md5;
- try{
- fis = new FileInputStream(filename);
- md5 = MessageDigest.getInstance("MD5");
- while((numRead=fis.read(buffer)) > 0) {
- md5.update(buffer,0,numRead);
- }
- fis.close();
- return toHexString(md5.digest());
- } catch (Exception e) {
- System.out.println("error");
- return null;
- }
- }
- }