MD5.java 2.43 KB
package com.server.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

/**
 * MD5
 */
public final class MD5 {

    private MD5() {
    }

    private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    public static String md5(String txt) {
        try {
            return md5(txt.getBytes("UTF-8"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String md5(String... txt) {
        return md5(StrUtils.joinString(",", txt));
    }

    public static String md5(byte[] data) {
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            byte[] bytes = data;
            mdTemp.update(bytes);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param file
     * @return
     * @throws IOException
     */
    public static String fileMd5(File file) throws Exception {
        try (FileInputStream in = new FileInputStream(file)) {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            FileChannel fChannel = in.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(16 * 1024);
            for (int count = fChannel.read(buffer); count != -1; count = fChannel.read(buffer)) {
                buffer.flip();
                md5.update(buffer);
                if (!buffer.hasRemaining()) {
                    buffer.clear();
                }
            }
            //
            byte[] md = md5.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception ex) {
            throw ex;
        }
    }
}