1

I've been working in an algorithm that I found in this link: Pure Lua implementation of md5 to use in an embedded system, but it uses strings as input.

For my specific application, the hash need to receive an hex array like that: 85202599ee7e0165ee32be43336755595955544554554747.

How can I change the function bellow to calculate the hash using the array above?

function md5.Calc(s)
  local msgLen=string.len(s)
  local padLen=56- msgLen % 64
  if msgLen % 64 > 56 then padLen=padLen+64 end
  if padLen==0 then padLen=64 end
  s=s..string.char(128)..string.rep(string.char(0),padLen-1)
  s=s..leIstr(8*msgLen)..leIstr(0)
  assert(string.len(s) % 64 ==0)
  local t=md5.consts
  local a,b,c,d=t[65],t[66],t[67],t[68]
  for i=1,string.len(s),64 do
    local X=leStrCuts(string.sub(s,i,i+63),4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4)
    assert(#X==16)
    X[0]=table.remove(X,1) -- zero based!
    a,b,c,d=md5.transform(a,b,c,d,X)
  end
  local swap=function (w) return beInt(leIstr(w)) end
  return string.format("%08x%08x%08x%08x",swap(a),swap(b),swap(c),swap(d))
end

return md5.Calc("85202599ee7e0165ee32be43336755595955544554554747"); -- returns: cc238dfd3cf48d588714774efeaf9a1f
-- but I need a return like that calculated in https://cryptii.com/pipes/md5-hash: c7e9f863554dc9a410c414f8758b307d
Nifim
  • 4,758
  • 2
  • 12
  • 31
Ctnalves
  • 11
  • 2

1 Answers1

0

Lua strings can hold binary data: each "character" then is one byte. This is what is being used in above code. You can see that characters 128 (0x80 or 0b10000000) and zero are used for the padding.

So you should not change the above code at all; instead you should decode the hexadecimal string to a binary string and use that as input to above function.

You can find an interesting, concise method of hex decoding here.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • And? Did you think this answer was useful? Please followup on your questions and indicate if answers are lacking detail or if they are acceptable by accepting them. – Maarten Bodewes Jul 05 '20 at 21:50