All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.afu.utils.encryption.Md5Encryption Maven / Gradle / Ivy

There is a newer version: 0.0.55-RELEASE
Show newest version
package io.afu.utils.encryption;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

public class Md5Encryption {

    public static String md5(File file) throws Exception {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        @SuppressWarnings("resource")
        FileInputStream fis = new FileInputStream(file);
        byte[] arr = new byte[1024 * 8];
        int len = 0;
        while ((len = fis.read(arr)) != -1) {
            md5.update(arr, 0, len);
        }
        return byteArrayToHex(md5.digest()).toLowerCase();
    }

    public static String byteArrayToHex(byte[] byteArray) {
        // 首先初始化一个字符数组,用来存放每个16进制字符
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        // new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方))
        char[] resultCharArray = new char[byteArray.length * 2];
        // 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去
        int index = 0;
        for (byte b : byteArray) {
            resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b & 0xf];
        }
        // 字符数组组合成字符串返回
        return new String(resultCharArray);
    }






}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy