package com.nokia.tsl_data.util;

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

public class CodecUtil {

    /**
     * 返回 路径对应的文件 的 md5
     */
    public static String MD5OfFile(String filePath) {
        try (InputStream inputStream = new FileInputStream(filePath)) {
            return MD5OfInputStream(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("获取MD5出错..." + e.getMessage());
        }
    }

    /**
     * 返回 文件 的 md5
     */
    public static String MD5OfFile(File file) {
        try (InputStream inputStream = new FileInputStream(file)) {
            return MD5OfInputStream(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("获取MD5出错..." + e.getMessage());
        }
    }

    /**
     * 返回 InputStream 的 md5
     */
    public static String MD5OfInputStream(InputStream inputStream) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer, 0, 1024)) != -1) {
                messageDigest.update(buffer, 0, length);
            }
            byte[] md5Bytes = messageDigest.digest();
            StringBuilder sb = new StringBuilder(40);
            for (byte x : md5Bytes) {
                if ((x & 0xff) >> 4 == 0) {
                    sb.append("0").append(Integer.toHexString(x & 0xff));
                } else {
                    sb.append(Integer.toHexString(x & 0xff));
                }
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
            throw new RuntimeException("获取MD5出错..." + e.getMessage());
        }
    }
}
