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

io.github.linmoure.utils.MD5Utils Maven / Gradle / Ivy

There is a newer version: 1.0.6
Show newest version
package io.github.linmoure.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {


    static MessageDigest getDigest() {
        try {
            return MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String md5Hex(String data, String charset) throws UnsupportedEncodingException {
        getDigest().digest(data.getBytes(charset));
        return byteArrayToHex(getDigest().digest(data.getBytes(charset)));
    }

    public static String byteArrayToHex(byte[] byteArray) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        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 - 2024 Weber Informatics LLC | Privacy Policy