Getting md5


Posted: 2008/04/01 15:35:13 | Source | More posts about Java Python Tutorial

Want to get MD5 ? Examples are in Python and Java

In Python: >>> import md5 >>> print md5.md5(“kushal”).hexdigest() ‘6ec44a1207a3d9506418c034679087b6’ Easy isn’t it !!

Now let us do the same in JAVA:

import java.security.MessageDigest;
import java.lang.String;

class MD5 { public static void main(String args[]) { try { MessageDigest digest = MessageDigest.getInstance(“MD5”); digest.update(“kushal”.getBytes()); System.out.println(byteArrayToHexString(digest.digest())); } catch (Exception e){ e.printStackTrace(); } }

public static String byteArrayToHexString(byte in[]) {
    byte ch = 0x00;
    int i = 0; 
    if (in == null || in.length <= 0)
        return null;
    String pseudo[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
    StringBuffer out = new StringBuffer(in.length * 2);

    while (i < in.length) {
        ch = (byte) (in[i] & 0xF0); 
        ch = (byte) (ch >>> 4);
        ch = (byte) (ch & 0x0F);    
        out.append(pseudo[ (int) ch]); 
        ch = (byte) (in[i] & 0x0F); 
        out.append(pseudo[ (int) ch]); 
        i++;
    }
    String rslt = new String(out);
    return rslt;
}    

}

I found that code on byteArrayToHexString somewhere in the net.

Update: As ignacio pointed in the comments that the md5 module is deprecated in Python 2.5, we have to use hashlib module instead. >>> import hashlib >>> h = hashlib.md5() >>> h.update(‘kushal’) >>> h.hexdigest() ‘6ec44a1207a3d9506418c034679087b6’

comments powered by Disqus
Contents © 2004-2014 Kushal Das - Powered by Shonku