Creating an MD5 String using Java
MD5 is a simple cryptographic hashing algorithm widely used for various application. In this tutorial im trying to generate MD5 value from a string and then compare it to mysql’s MD5 query result.
This is my java code to generate MD5, im using java’s MessageDigest.
package com.edw.util; import java.security.MessageDigest; import org.junit.Test; /** * * @author edw */ public class MD5Test { public MD5Test() { } public String hexStringFromBytes(byte[] b) { char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; String hex = ""; int msb; int lsb = 0; int i; for (i = 0; i < b.length; i++) { msb = ((int) b[i] & 0x000000FF) / 16; lsb = ((int) b[i] & 0x000000FF) % 16; hex = hex + hexChars[msb] + hexChars[lsb]; } return hex; } @Test public void testMD5() throws Exception { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); // get md5 for word "PASSWORD" digest.update("PASSWORD".getBytes()); byte[] passwordBytes = digest.digest(); // result = 319f4d26e3c536b5dd871bb2c52e3178 System.out.println(hexStringFromBytes(passwordBytes)); } }
compared to mysql’s md5 function
you can see that MD5 strings generated by java and mysql are both the same.
(H)
No Comments