MD5Utils

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**

  • Create by tanx on 2019/4/30
    */
    public class Md5Utils {
    private static Logger LOG = LoggerFactory.getLogger(Md5Utils.class);
    private static final int bufferSize = 16 * 1024;

    public static String fileMD5(String inputFilePath) throws IOException {
    try (
    FileInputStream fileInputStream = new FileInputStream(inputFilePath);
    ) {
    return fileMD5(fileInputStream);
    } catch (Exception e) {
    return null;
    }
    }

    public static String fileMD5(File inputFile) throws IOException {
    try (
    FileInputStream fileInputStream = new FileInputStream(inputFile);
    ) {
    return fileMD5(fileInputStream);
    } catch (Exception e) {
    return null;
    }
    }

    /**

    • 可处理大文件
    • @param inputStream
    • @return
    • @throws IOException
      */
      public static String fileMD5(InputStream inputStream) throws IOException, NoSuchAlgorithmException {
      // 拿到一个MD5转换器(同样,这里可以换成SHA1)
      MessageDigest messageDigest = MessageDigest.getInstance(“MD5”);
      try (
      // 使用DigestInputStream
      DigestInputStream digestInputStream = new DigestInputStream(inputStream, messageDigest);
      ) {
      // read的过程中进行MD5处理,直到读完文件
      byte[] buffer = new byte[bufferSize];
      while (digestInputStream.read(buffer) > 0) ;
      // 获取最终的MessageDigest
      messageDigest = digestInputStream.getMessageDigest();
      // 拿到结果,也是字节数组,包含16个元素
      BigInteger bigInteger = new BigInteger(1, messageDigest.digest());
      // 同样,把字节数组转换成字符串
      return bigInteger.toString(16);
      } catch (Exception e) {
      return null;
      }
      }
      }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值