1

I'm trying to calculate the RIPEMD160 hash in matlab for some data represented by a hex string. I found the following java class and compiled it for jvm 1.6

http://developer.nokia.com/Community/Wiki/RIPEMD160_encryption_in_JavaME

the following code works perfectly in matlab for hashing strings:

clear all

% add folder with class file to java path 
functions_folder = strcat(pwd,filesep,'functions'); 
javaaddpath(functions_folder)

% string to hash 
string_to_hash = 'test12345';

% convert to java String 
str_to_hash_java = javaObject('java.lang.String',uint8(string_to_hash));

% pass in string and convert output to char array 
mystr = char(RIPEMD160.RIPEMD160String(str_to_hash_java))

Now my problem comes about when I try to hash some binary data represented by a hex string. The hash output is correct for hex values of 7f or smaller, but once I have 8 bits (>= 80) it no longer gives the correct answer. I can't seem to find the problem. Here is my code:

clear all

% add folder with class file to java path
functions_folder = strcat(pwd,filesep,'functions');
javaaddpath(functions_folder)

% data to hash in hex format
hex_string_in = '80';

hex_string_in_length = length(hex_string_in);

% split every to characters and calculate the data in each byte
for i=1:hex_string_in_length/2
    data_uint8_array(1,i) = uint8(hex2dec(hex_string_in(2*i-1:2*i)));
end

% constructor
x = RIPEMD160;

% pass in binary data
x.update(data_uint8_array)

% get hash in binary format
hash_out_bin = x.digestBin();

% typecast binary data into unit8 primitive
hash_out_unit8=typecast(hash_out_bin,'uint8');

% convert to hex
hash_out_hex = dec2hex(hash_out_unit8)';

% pad with zeros if bytes all smaller than hex(80)
if(size(hash_out_hex,1))==1
    hash_out_hex=[repmat('0',[1 size(hash_out_hex,2)]);hash_out_hex];
end

% final formatting, convert to lowercase
hash_out_hex = lower(hash_out_hex(:)')

for an input of '7f' it produces the correct hash of c8297aad716979548921b2e8e26ca8f20061dbef

but for '80' is gives e633ca40d977e24a1ffd56b7a992e99b48d13359 instead of the correct result b436441e6bb882fe0a0fa0320cb2d97d96b4d1bc

Thanks.

1 Answers1

0

You are passing strings to your Java code instead of regular byte arrays. Not all bytes are representations of valid character encodings. Therefore you are likely to loose information. Only hash bytes, without any conversion. If strings are required use base 64 encoding/decoding.

str_to_hash_java should not be needed.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263