public static String MD5(Object obj) throws java.security.NoSuchAlgorithmException { String buffer = obj.toString(); java.security.MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(buffer.getBytes()); byte[] b = digest.digest(); buffer = ""; for (int i=0; i < b.length; i++) { buffer += Integer.toString((b[i] & 0xff ) + 0x100, 16).substring(1); } return buffer; }
Hi,
I found this piece of code on the net while i was curious about md5 encryption. I tried to figure some things out but since I'm new, I'm not too sure why.
1. Why must I do digest.update? I tried looking in the documentation, but I couldn't get it.
2. What does the offset do?update
public void update(byte[] input,
int offset,
int len)
Updates the digest using the specified array of bytes, starting at the specified offset.
Parameters:
input - the array of bytes.
offset - the offset to start from in the array of bytes.
len - the number of bytes to use, starting at offset.
3. I do not get it why must this line be done.for (int i=0; i < b.length; i++) { buffer += Integer.toString((b[i] & 0xff ) + 0x100, 16).substring(1); }
I found out that I could actually do the below md5 hashing, but it truncates the 0 infront.
import java.security.*; import java.math.*; public class MD5 { public static void main(String args[]) throws Exception{ String s="This is a test"; MessageDigest m=MessageDigest.getInstance("MD5"); m.update(s.getBytes(),0,s.length()); System.out.println("MD5: "+new BigInteger(1,m.digest()).toString(16)); } }
For both type of md5 hashing, I used the string, "f78spx"
Regards,
Zepx