sha1加密
```lua
-- 加载bit32库,Lua 5.2及之前版本需要
local bit = require("bit32")
local function leftrotate(x, c)
return bit.bor(bit.lshift(x, c), bit.rshift(x, 32 - c))
end
local function tohex(num)
return string.format("%08x", num)
end
local function preprocess(msg)
local len = #msg * 8
msg = msg .. "\128" -- append the bit '1' to the message
while (#msg + 8) % 64 ~= 0 do
msg = msg .. "\0"
end
-- Append the length in bits at the end of the buffer.
msg = msg .. string.pack(">I8", len)
return msg
end
local function sha1(msg)
msg = preprocess(msg)
-- Initial hash values
local h0, h1, h2, h3, h4 = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0
for i = 1, #msg, 64 do
local chunk = msg:sub(i, i + 63)
local w = {}
for j = 1, 16 do
w[j] = string.unpack(">I4", chunk, (j - 1) * 4 + 1)
end
-- Extend the sixteen 32-bit words into eighty 32-bit words:
for j = 17, 80 do
w[j] = leftrotate(bit.bxor(w[j-3], w[j-8], w[j-14], w[j-16]), 1)
end
local a, b, c, d, e = h0, h1, h2, h3, h4
for j = 1, 80 do
local f, k
if j <= 20 then
f = bit.bor(bit.band(b, c), bit.band(bit.bnot(b), d))
k = 0x5A827999
elseif j <= 40 then
f = bit.bxor(b, c, d)
k = 0x6ED9EBA1
elseif j <= 60 then
f = bit.bor(bit.band(b, c), bit.band(b, d), bit.band(c, d))
k = 0x8F1BBCDC
else
f = bit.bxor(b, c, d)
k = 0xCA62C1D6
end
local temp = leftrotate(a, 5) + f + e + k + w[j]
e = d
d = c
c = leftrotate(b, 30)
b = a
a = temp
end
h0 = bit.band(h0 + a, 0xFFFFFFFF)
h1 = bit.band(h1 + b, 0xFFFFFFFF)
h2 = bit.band(h2 + c, 0xFFFFFFFF)
h3 = bit.band(h3 + d, 0xFFFFFFFF)
h4 = bit.band(h4 + e, 0xFFFFFFFF)
end
return tohex(h0) .. tohex(h1) .. tohex(h2) .. tohex(h3) .. tohex(h4)
end
-- Example usage
log(sha1("adfadfadfaf"))
```