How to calculate hash sum of a string (using java)?

Asked by Sebastian Holmqvist on 6 Aug 2012
Latest activity Answered by Sebastian Holmqvist on 6 Aug 2012

Couldn't find this very easily (without including a bunch of c-mex files etc) so I thought I'd post it here for future reference. I prefer using java methods to avoid dependencies.

Question:

Using java, how to create a MD5 (or SHA1 etc) hash sum of a string?

0 Comments

Sebastian Holmqvist

Products

1 Answer

Answer by Sebastian Holmqvist on 6 Aug 2012
Edited by Sebastian Holmqvist on 6 Aug 2012
Accepted answer

Solution:

The trick here is to input an ascii representation of your string (hence, the double(string) call). MessageDigest outputs 16 bytes which represents 32 chars. So we use BigInteger to convert the bytes to that radix.

import java.security.*;
import java.math.*;
md = MessageDigest.getInstance('MD5');
hash = md.digest(double('Your string.'));
bi = BigInteger(1, hash);
char(bi.toString(16))
ans = 
b99e5935368933bafefed10b99bb0489

0 Comments

Sebastian Holmqvist

Contact us