[JAVA] Returns the string as md5 hash

Convert character strings to md5Hash

Well, it's my memo. It seems that there is 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 will be an arbitrary character string. The hashed result is the value of str.


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

 * md5Hash
 *Converts the input character string to md5Hash and returns it

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

            //Instantiate a message digest
            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 result.


String to be hashed: 12345
String after hashing: 827ccb0eea8a706c4c34a16891f84e7b


How to find MD5 digest value in Java [Java] MD5 hashing of strings

Recommended Posts

Returns the string as md5 hash
Read the file under the classpath as a character string with spring