在Matlab中使用RIPEMD160哈希

时间:2014-01-13 09:11:02

标签: matlab hash cryptography ripemd

我正在尝试在matlab中计算由十六进制字符串表示的某些数据的RIPEMD160哈希值。我找到了以下java类并为jvm 1.6编译了它

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

以下代码在matlab中完美地用于散列字符串:

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))

现在我的问题出现在我尝试散列由十六进制字符串表示的一些二进制数据时。哈希输出对于7f或更小的十六进制值是正确的,但是一旦我有8位(> = 80)它就不再给出正确的答案。我似乎无法找到问题。这是我的代码:

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(:)')

输入'7f'会产生正确的哈希值c8297aad716979548921b2e8e26ca8f20061dbef

但是'80'是给出e633ca40d977e24a1ffd56b7a992e99b48d13359而不是正确的结果b436441e6bb882fe0a0fa0320cb2d97d96b4d1bc

感谢。

1 个答案:

答案 0 :(得分:0)

您将字符串传递给Java代码而不是常规字节数组。并非所有字节都是有效字符编码的表示。因此,您可能会丢失信息。只有哈希字节,没有任何转换。如果需要字符串,请使用base 64编码/解码。

str_to_hash_java不需要。