warpstack
warpstack

Reputation: 145

Matlab-Java MD5 giving incorrect hashes

I am trying to get the md5 hash of a char array. Below is my code.

data = unicode2native(data, 'UTF-8');
K = java.security.MessageDigest.getInstance('MD5');
md5 = reshape(dec2hex(typecast(K.digest(data), 'UINT8')), 1, 32);

Wikipedia lists some example hash values for strings. For example, the input of "The quick brown fox jumps over the lazy dog" should yield a md5 hash of 9e107d9d372bb6826bd81d3542a419d6, however my implementation gives the following 917932b86d134a1de0dd7b62b8d52496 which obviously does not match.

I am not quite sure where the problem may be but perhaps it has to do with the char conversion on the first line.

Upvotes: 0

Views: 153

Answers (2)

Oleg
Oleg

Reputation: 10676

No, it's the reshape that it is off:

s = unicode2native('The quick brown fox jumps over the lazy dog','UTF-8');
K = java.security.MessageDigest.getInstance('MD5');
out = dec2hex(typecast(K.digest(s),'uint8'))

9E
10
7D
9D
37
2B
B6
82
6B
D8
1D
35
42
A4
19
D6

The correct reshape:

reshape(out',1,[])

Upvotes: 4

Daniel
Daniel

Reputation: 36710

The problem is your use of reshape, remove that and you will already be able to recognize the hash.

data='The quick brown fox jumps over the lazy dog'
data2 = unicode2native(data, 'ASC-II');
K = java.security.MessageDigest.getInstance('MD5');
md5 = dec2hex(typecast(K.digest(data2), 'UINT8')).';
md5 = md5(:).'

Upvotes: 1

Related Questions