Md5Sum.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /**
  17. *
  18. */
  19. package org.maxkey.crypto;
  20. import java.io.File;
  21. import java.io.FileInputStream;
  22. import java.io.FileNotFoundException;
  23. import java.io.IOException;
  24. import java.nio.MappedByteBuffer;
  25. import java.nio.channels.FileChannel;
  26. import java.security.MessageDigest;
  27. /**
  28. * 类似linux或Unix上,md5sum是用来计算和校验文件报文摘要的工具程序
  29. * @author Crystal.Sea
  30. *
  31. */
  32. public class Md5Sum {
  33. /**
  34. *
  35. */
  36. public Md5Sum() {
  37. }
  38. public static String produce(File file) throws FileNotFoundException {
  39. String md5value = null;
  40. FileInputStream in = new FileInputStream(file);
  41. try {
  42. MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
  43. MessageDigest messageDigest = MessageDigest.getInstance("MD5");
  44. messageDigest.update(byteBuffer);
  45. byte[] bCipher=messageDigest.digest();
  46. md5value=HexUtils.bytes2HexString(bCipher);
  47. } catch (Exception e) {
  48. e.printStackTrace();
  49. } finally {
  50. if (null != in) {
  51. try {
  52. in.close();
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. }
  58. md5value+=" *"+file.getName();
  59. return md5value;
  60. }
  61. public static boolean check(File file,String md5String) throws FileNotFoundException{
  62. String md5value = produce( file);
  63. return md5value.equals(md5String)?true:false;
  64. }
  65. }