HashXiZhiUtil.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package com.fuzamei.util;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.InputStream;
  5. import java.security.MessageDigest;
  6. public class HashXiZhiUtil {
  7. public static byte[] getMd5(String input) {
  8. try {
  9. byte[] by = input.getBytes("UTF-8");
  10. MessageDigest det = MessageDigest.getInstance("SHA");
  11. return det.digest(by);
  12. } catch (Exception e) {
  13. e.printStackTrace();
  14. }
  15. return null;
  16. }
  17. public static String bytesToHexString(byte[] src) {
  18. StringBuilder stringBuilder = new StringBuilder("");
  19. if (src == null || src.length <= 0) {
  20. return null;
  21. }
  22. for (int i = 0; i < src.length; i++) {
  23. int v = src[i] & 0xFF;
  24. String hv = Integer.toHexString(v);
  25. if (hv.length() < 2) {
  26. stringBuilder.append(0);
  27. }
  28. stringBuilder.append(hv);
  29. }
  30. return stringBuilder.toString();
  31. }
  32. public static String getMD5Checksum(String filename) throws Exception {
  33. return getMD5Checksum(new File(filename));
  34. }
  35. public static String getMD5Checksum(File file) throws Exception {
  36. byte[] b = createChecksum(file);
  37. String result = "";
  38. for (int i = 0; i < b.length; i++) {
  39. result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);// 加0x100是因为有的b[i]的十六进制只有1位
  40. }
  41. return result;
  42. }
  43. public static byte[] createChecksum(String filename) throws Exception {
  44. return createChecksum(new File(filename));
  45. }
  46. public static byte[] createChecksum(File file) throws Exception {
  47. InputStream fis = new FileInputStream(file); // <span style="color:
  48. // rgb(51, 51, 51);
  49. // font-family: arial;
  50. // font-size: 13px;
  51. // line-height:
  52. // 20px;">将流类型字符串转换为String类型字符串</span>
  53. byte[] buffer = new byte[1024];
  54. MessageDigest complete = MessageDigest.getInstance("MD5"); // 如果想使用SHA-1或SHA-256,则传入SHA-1,SHA-256
  55. int numRead;
  56. do {
  57. numRead = fis.read(buffer); // 从文件读到buffer,最多装满buffer
  58. if (numRead > 0) {
  59. complete.update(buffer, 0, numRead); // 用读到的字节进行MD5的计算,第二个参数是偏移量
  60. }
  61. } while (numRead != -1);
  62. fis.close();
  63. return complete.digest();
  64. }
  65. /*
  66. * public static void main(String[] args) {
  67. * System.out.println(HashXiZhiUtil.getMd5("D:\\xiangnu\\123.doc"));
  68. * System.out.println(HashXiZhiUtil.bytesToHexString(HashXiZhiUtil.getMd5(
  69. * "D:\\xiangnu\\123.doc")));
  70. * System.out.println(HashXiZhiUtil.bytesToHexString(HashXiZhiUtil.getMd5(
  71. * "D:\\xiangnu\\123.doc"))); }
  72. */
  73. }