[Java] Md5 hash the string and return

less than 1 minute read

Convert string to md5Hash

Well, my own memo. There seems to be a library, so I don’t use it. This method uses MessageDigest.

The strHash part of the source below is the string you want to hash. It can be any string. The hashed result is the value of str.


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

 * md5Hash
 * Return the input character string as md5Hash

public class md5Hash {
    public static void main(String[] args) {
        /** String to be hashed: strHash */
        String strHash = "12345";
        System.out.println("String to hash:" + strHash);

            // create a message digest instance
            MessageDigest md5 = MessageDigest.getInstance("MD5");

            byte[] result = md5.digest(strHash.getBytes());
            // Convert to hexadecimal and arrange digits
            int[] i = new int[result.length];
            StringBuffer sb = new StringBuffer();
            for (int j=0; j <result.length; j++){
                i[j] = (int)result[j] & 0xff;
                if (i[j]<=15){
            String str = sb.toString();
            System.out.println("String after hashing:" + str);

        } catch (NoSuchAlgorithmException x){


If you execute the above, you will get the following results.


String to hash: 12345
String after hashing: 827ccb0eea8a706c4c34a16891f84e7b


How to calculate MD5 digest value in Java [Java] MD5 hash of character string