AI翻译的,你看看对不对,不对就算了;www
local function md5(str)
-- Function to compute MD5 hash
return require('md5').sumhexa(str)
end
local function microtime()
return os.time() + os.clock()
end
local function base64_encode(input)
return (require('base64').encode(input))
end
local function base64_decode(input)
return (require('base64').decode(input))
end
local function chr(value)
return string.char(value)
end
local function ord(char)
return string.byte(char)
end
local function encryption_function(str, operation, key, expiry)
operation = operation or 'DECODE'
key = key or ''
expiry = expiry or 0
local ckey_length = 4
key = md5(key)
-- 密匙a会参与加解密
local keya = md5(key:sub(1, 16))
-- 密匙b会用来做数据完整性验证
local keyb = md5(key:sub(17, 32))
-- 密匙c用于变化生成的密文
local keyc
if ckey_length > 0 then
if operation == 'DECODE' then
keyc = str:sub(1, ckey_length)
else
local md5_time = md5(tostring(microtime()))
local start = #md5_time - ckey_length + 1
keyc = md5_time:sub(start, start + ckey_length - 1)
end
else
keyc = ''
end
local cryptkey = keya .. md5(keya .. keyc)
local strbuf
if operation == 'DECODE' then
str = str:sub(ckey_length + 1)
strbuf = base64_decode(str)
else
if expiry > 0 then
expiry = expiry + os.time()
end
local tmpstr = tostring(expiry)
if #tmpstr >= 10 then
str = tmpstr:sub(1, 10) .. md5(str .. keyb):sub(1, 16) .. str
else
local count = 10 - #tmpstr
tmpstr = string.rep('0', count) .. tmpstr
str = tmpstr .. md5(str .. keyb):sub(1, 16) .. str
end
strbuf = str
end
local box = {}
for i = 0, 255 do
box[i] = i
end
local rndkey = {}
for i = 0, 255 do
rndkey[i] = ord(cryptkey:sub((i % #cryptkey) + 1, (i % #cryptkey) + 1))
end
local j = 0
for i = 0, 255 do
j = (j + box[i] + rndkey[i]) % 256
box[i], box[j] = box[j], box[i]
end
local s = ''
strbuf = {strbuf:byte(1, #strbuf)}
local a, b = 0, 0
for i = 1, #strbuf do
a = (a + 1) % 256
b = (b + box[a]) % 256
box[a], box[b] = box[b], box[a]
s = s .. chr(ord(string.char(strbuf[i])) ~ (box[(box[a] + box[b]) % 256]))
end
if operation == 'DECODE' then
if (s:sub(1, 10) == '0' or tonumber(s:sub(1, 10)) > os.time()) and
s:sub(11, 26) == md5(s:sub(27) .. keyb):sub(1, 16) then
s = s:sub(27)
else
s = ''
end
else
s = base64_encode(s)
s = s:gsub('=', '')
s = keyc .. s
end
return s
end
|