Advertisement
Tatantyler

Key Derivation

May 13th, 2013
373
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.02 KB | None | 0 0
  1. -- HMAC-SHA256 based key derivation
  2.  
  3. if SHA2 or (not os.loadAPI("SHA2")) then
  4.     error("Could not find SHA2 API")
  5. end
  6.  
  7. local function internal_prfLoop(pw, salt, iter, i)
  8.     local i_bytes = {
  9.         bit.band(bit.brshift(bit.band(i, 0xFF000000), 24), 0xFF),
  10.         bit.band(bit.brshift(bit.band(i, 0xFF0000), 16), 0xFF),
  11.         bit.band(bit.brshift(bit.band(i, 0xFF00), 8), 0xFF),
  12.         bit.band(i, 0xFF),
  13.     }
  14.     for i=1, #salt do
  15.         table.insert(i_bytes, salt[i])
  16.     end
  17.     local t = SHA2.hashToBytes(SHA2.hmac(i_bytes, pw))
  18.     local result = {}
  19.     for j=1, 32 do
  20.         result[j] = t[i]
  21.     end
  22.     for j=2, iter do
  23.         local t2 = SHA2.hashToBytes(SHA2.hmac(t, pw))
  24.         for i=1, 32 do
  25.             result[i] = bit.bxor(result[i], t2[i])
  26.         end
  27.         t = t2
  28.     end
  29.     return result
  30. end
  31.  
  32. function deriveKey(pw, salt, iter, length)
  33.     -- Hlen is 32
  34.     local output = {}
  35.     for i=1, math.ceil(length/32) do
  36.         local t = internal_prfLoop(pw, salt, iter, i)
  37.         for j=1, 32 do
  38.             table.insert(output, j)
  39.             if #output >= length then
  40.                 return output
  41.             end
  42.         end
  43.     end
  44.     return output
  45. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement