package com.sifang.modules.esign.utils;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;

public class ContentMD5Utils{

    /***
     * 计算文件的Content-MD5
     * @return
     */
    public static String getFileContentMD5(MultipartFile file) {
        // 获取文件MD5的二进制数组（128位）
        byte[] bytes = getFileMD5Bytes128(file);
        // 对文件MD5的二进制数组进行base64编码
        return new String(Base64.encodeBase64(bytes));
    }

    /***
     * 获取文件MD5-二进制数组（128位）
     *
     * @return
     * @throws IOException
     */
    public static byte[] getFileMD5Bytes128(MultipartFile file){
        byte[] md5Bytes = null;
        try {
           /* InputStream fis=new FileInputStream(new File("E:\\Hx\\备件导入表格\\2.pdf"));*/
            InputStream fis = file.getInputStream();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = fis.read(buffer, 0, 1024)) != -1) {
                md5.update(buffer, 0, length);
            }
            md5Bytes = md5.digest();
            fis.close();
        }catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }catch (NoSuchAlgorithmException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        return md5Bytes;
    }

    public static void main(String[] args) {


    }

}
