123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- package com.fuzamei.util;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.InputStream;
- import java.security.MessageDigest;
- public class HashXiZhiUtil {
- public static byte[] getMd5(String input) {
- try {
- byte[] by = input.getBytes("UTF-8");
- MessageDigest det = MessageDigest.getInstance("SHA");
- return det.digest(by);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- public static String bytesToHexString(byte[] src) {
- StringBuilder stringBuilder = new StringBuilder("");
- if (src == null || src.length <= 0) {
- return null;
- }
- for (int i = 0; i < src.length; i++) {
- int v = src[i] & 0xFF;
- String hv = Integer.toHexString(v);
- if (hv.length() < 2) {
- stringBuilder.append(0);
- }
- stringBuilder.append(hv);
- }
- return stringBuilder.toString();
- }
- public static String getMD5Checksum(String filename) throws Exception {
- return getMD5Checksum(new File(filename));
- }
-
- public static String getMD5Checksum(File file) throws Exception {
- byte[] b = createChecksum(file);
- String result = "";
-
- for (int i = 0; i < b.length; i++) {
- result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);// 加0x100是因为有的b[i]的十六进制只有1位
- }
- return result;
- }
- public static byte[] createChecksum(String filename) throws Exception {
- return createChecksum(new File(filename));
- }
- public static byte[] createChecksum(File file) throws Exception {
- InputStream fis = new FileInputStream(file); // <span style="color:
- // rgb(51, 51, 51);
- // font-family: arial;
- // font-size: 13px;
- // line-height:
- // 20px;">将流类型字符串转换为String类型字符串</span>
- byte[] buffer = new byte[1024];
- MessageDigest complete = MessageDigest.getInstance("MD5"); // 如果想使用SHA-1或SHA-256,则传入SHA-1,SHA-256
- int numRead;
- do {
- numRead = fis.read(buffer); // 从文件读到buffer,最多装满buffer
- if (numRead > 0) {
- complete.update(buffer, 0, numRead); // 用读到的字节进行MD5的计算,第二个参数是偏移量
- }
- } while (numRead != -1);
- fis.close();
- return complete.digest();
- }
- /*
- * public static void main(String[] args) {
- * System.out.println(HashXiZhiUtil.getMd5("D:\\xiangnu\\123.doc"));
- * System.out.println(HashXiZhiUtil.bytesToHexString(HashXiZhiUtil.getMd5(
- * "D:\\xiangnu\\123.doc")));
- * System.out.println(HashXiZhiUtil.bytesToHexString(HashXiZhiUtil.getMd5(
- * "D:\\xiangnu\\123.doc"))); }
- */
- }
|