Creating a hash codes from strings is a common programming task. MD5 is a very popular and commonly used hashing algorithm. Creating an MD5 hash code from a String in Java can be easily done, and is shown in the code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package com.bigdatums.hashing; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class BdHashingUtils { public static String md5OfString(String str){ StringBuilder sb = new StringBuilder(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] digest = md.digest(); for(byte dByte : digest){ sb.append(String.format("%02x", dByte & 0xff)); } } catch(NoSuchAlgorithmException e) { System.out.println(e); } catch(NullPointerException e){ System.out.println("NullPointerException: Please provide a valid string"); } return sb.toString(); } public static void main(String[] args){ System.out.println(BdHashingUtils.md5OfString("this is a test string")); System.out.println(BdHashingUtils.md5OfString(null)); } } |
The code above is does several things: Creates a StringBuilder object to