123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- package com.onemap.api.util;
- import org.apache.commons.codec.binary.Hex;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.nio.charset.StandardCharsets;
- import java.security.MessageDigest;
- /**
- * Md5加密方法
- *
- * @author ruoyi
- */
- public class Md5Utils
- {
- private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);
- private static byte[] md5(String s)
- {
- MessageDigest algorithm;
- try
- {
- algorithm = MessageDigest.getInstance("MD5");
- algorithm.reset();
- algorithm.update(s.getBytes("UTF-8"));
- byte[] messageDigest = algorithm.digest();
- return messageDigest;
- }
- catch (Exception e)
- {
- log.error("MD5 Error...", e);
- }
- return null;
- }
- private static final String toHex(byte hash[])
- {
- if (hash == null)
- {
- return null;
- }
- StringBuffer buf = new StringBuffer(hash.length * 2);
- int i;
- for (i = 0; i < hash.length; i++)
- {
- if ((hash[i] & 0xff) < 0x10)
- {
- buf.append("0");
- }
- buf.append(Long.toString(hash[i] & 0xff, 16));
- }
- return buf.toString();
- }
- public static String hash(String s)
- {
- try
- {
- return new String(toHex(md5(s)).getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
- }
- catch (Exception e)
- {
- log.error("not supported charset...{}", e);
- return s;
- }
- }
- /**
- * 获取一个文件的md5值(可处理大文件)
- * @return md5 value
- */
- public static String getMD5(File file) {
- FileInputStream fileInputStream = null;
- try {
- MessageDigest MD5 = MessageDigest.getInstance("MD5");
- fileInputStream = new FileInputStream(file);
- byte[] buffer = new byte[8192];
- int length;
- while ((length = fileInputStream.read(buffer)) != -1) {
- MD5.update(buffer, 0, length);
- }
- return new String(Hex.encodeHex(MD5.digest()));
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- } finally {
- try {
- if (fileInputStream != null){
- fileInputStream.close();
- }
- } catch (IOException e) {
- System.out.println(e.getMessage());
- }
- }
- }
- }
|