- 獲取字符串的MD5摘要
原文更詳細: http://www.weixuehao.com/archives/474
代碼如下:
import java.security.MessageDigest; public class Md5Test { // main測試類 public static void main(String[] args) { String result = getMD5("aaa"); System.out.println(result); } /** * 生成md5 * * @param message * @return */ public static String getMD5(String message) { String md5str = ""; try { // 1 創建一個提供信息摘要算法的對象,初始化為md5算法對象 MessageDigest md = MessageDigest.getInstance("MD5"); // 2 將消息變成byte數組 byte[] input = message.getBytes(); // 3 計算后獲得字節數組,這就是那128位了 byte[] buff = md.digest(input); // 4 把數組每一字節(一個字節占八位)換成16進制連成md5字符串 md5str = bytesToHex(buff); } catch (Exception e) { e.printStackTrace(); } return md5str; } /** * 二進制轉十六進制 * * @param bytes * @return */ public static String bytesToHex(byte[] bytes) { StringBuffer md5str = new StringBuffer(); // 把數組每一字節換成16進制連成md5字符串 int digital; for (int i = 0; i < bytes.length; i++) { digital = bytes[i]; if (digital < 0) { digital += 256; } if (digital < 16) { md5str.append("0"); } md5str.append(Integer.toHexString(digital)); } return md5str.toString().toUpperCase(); } }
- 獲取文件的MD5摘要
原文:http://liuxiang8484.blog.163.com/blog/static/734790972011101093250899/
java代碼:
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.MessageDigest; public class FileGetMD5 { // 16進制使用字符數組 static char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /** * 對文件全文生成MD5摘要 * * @param file 要加密的文件 * @return MD5摘要碼 */ public static String getMD5(File file) { FileInputStream fis = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); fis = new FileInputStream(file); byte[] buffer = new byte[2048]; int length = -1; while ((length = fis.read(buffer)) != -1) { md.update(buffer, 0, length); } byte[] b = md.digest(); return byteToHexString(b); // 16位加密 // return byteToHexString(b).substring(8, 24); } catch (Exception ex) { ex.printStackTrace(); return null; } finally { try { fis.close(); } catch (IOException ex) { ex.printStackTrace(); } } } /** * 把byte[]數組轉換成十六進制字符串表示形式 * * @param tmp 要轉換的byte[] * @return 十六進制字符串表示形式 */ private static String byteToHexString(byte[] tmp) { String md5str; // 用字節表示就是 16 個字節 char str[] = new char[16 * 2]; // 每個字節用 16 進制表示的話,使用兩個字符, // 所以表示成 16 進制需要 32 個字符 int k = 0; // 表示轉換結果中對應的字符位置 for (int i = 0; i < 16; i++) { // 從第一個字節開始,對 MD5 的每一個字節 // 轉換成 16 進制字符的轉換 byte byte0 = tmp[i]; // 取第 i 個字節 str[k++] = hexdigits[byte0 >>> 4 & 0xf]; // 取字節中高 4 位的數字轉換,>>> 為邏輯右移,將符號位一起右移 str[k++] = hexdigits[byte0 & 0xf]; // 取字節中低 4 位的數字轉換 } md5str = new String(str); // 換后的結果轉換為字符串 return md5str; } public static void main(String arg[]) { System.out.println(getMD5(new File("D:\\files\\test.csv"))); } }