You'd be surprised how difficult it was to find a 'pure' lua sha1 but I
eventually did. It emulates bit operations using tables so it's slow but I only need it occassionally so the overhead isn't significant.
The main problem is most implementations I found rely on either the 'bit' library or something highlevel like crypto or ssl. I tried implementing the bit library functions using spring or pure lua equivalents but the results weren't consistent.
Code: Select all
--[[
BIT LIBRARY
--]]
local w32 = include('w32_ops.h.lua')
local band = math.bit_and
local bor = math.bit_or
local bnot = math.bit_inv
local bxor = math.bit_xor
--local lshift = bit.lshift
--local rshift = bit.rshift
--local tobit = bit.tobit
local function lshift(x, by)
return x * 2 ^ by
end
local function rshift(x, by)
return math.floor(x / 2 ^ by)
end
--local bror = bit.ror
--local brol = bit.rol
-- bror(b, n) ((b << (32-n)) | (b >> n))
-- brol(b, n) ((b << n) | (b >> (32-n)))
local function bror(x, by)
return bor(lshift(x,(32-by)),rshift(x,by))
end
local function brol(x, by)
return bor(lshift(x,by),rshift(x,(32-by)))
end
local function test(v1,v2)
local Log = Spring.Echo
Log('v1 (' .. v1 .. ') = ' .. w32.w32_to_bit_string(v1))
Log('v2 (' .. v2 .. ') = ' .. w32.w32_to_bit_string(v2))
Log(v1 .. ' >> ' .. v2 .. ' = ' .. rshift(v1,v2))
Log(v1 .. ' >>> ' .. v2 .. ' = ' .. bror(v1,v2))
Log(v1 .. ' << ' .. v2 .. ' = ' .. lshift(v1,v2))
Log(v1 .. ' & ' .. v2 .. ' = ' .. band(v1,v2))
Log(v1 .. ' | ' .. v2 .. ' = ' .. bor(v1,v2))
Log(v1 .. ' ^ ' .. v2 .. ' = ' .. bxor(v1,v2))
Log(v1 .. ' ~ = ' .. bnot(v1), w32.w32_to_bit_string(v1), w32.w32_to_bit_string(bnot(v1)))
end
test(0xffffff,2)
--test(128,1)
return {
band = band,
bor = bor,
bxor = bxor,
bnot = bnot,
lshift = lshift,
rshift = rshift,
brol = brol,
bror = bror
}