[JavaScript] 纯文本查看 复制代码
-- LuaRocks安装lua-resty-string 实现 md5 base64
local md5 = require("resty.string").to_hex(require("resty.hash").md5)
local base64_encode, base64_decode = require("resty.string").to_base64, require("resty.string").from_base64
function encrypt_decrypt(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(string.sub(key, 1, 16))
-- 密匙b会用来做数据完整性验证
local keyb = md5(string.sub(key, 17, 32))
-- 密匙c用于变化生成的密文
local keyc
if ckey_length then
if operation == 'DECODE' then
keyc = string.sub(str, 1, ckey_length)
else
local md5_time = md5(os.time() * 1000) -- Lua没有microtime,使用os.time()代替
local start = #md5_time - ckey_length + 1
keyc = string.sub(md5_time, start, start + ckey_length - 1)
end
else
keyc = ''
end
local cryptkey = keya .. md5(keya .. keyc)
local strbuf
if operation == 'DECODE' then
str = string.sub(str, ckey_length + 1)
strbuf = base64_decode(str)
else
expiry = expiry and os.difftime(os.time(), -expiry) or 0
local tmpstr = tostring(expiry)
if #tmpstr >= 10 then
str = string.sub(tmpstr, 1, 10) .. string.sub(md5(str .. keyb), 1, 16) .. str
else
local count = 10 - #tmpstr
for i = 1, count do
tmpstr = '0' .. tmpstr
end
str = tmpstr .. string.sub(md5(str .. keyb), 1, 16) .. str
end
strbuf = str
end
local box = {}
for i = 0, 255 do
box[i + 1] = i + 1
end
local rndkey = {}
for i = 0, 255 do
rndkey[i + 1] = string.byte(cryptkey, (i + 1) % #cryptkey + 1)
end
for j, i = 0, 256 do
j = (j + box[i + 1]) % 256 + 1
box[i + 1], box[j] = box[j], box[i + 1]
end
-- 核心加解密部分
local s = ''
for a, i = 0, #strbuf do
a = (a + 1) % 256 + 1
j = (j + box[a]) % 256 + 1
box[a], box[j] = box[j], box[a]
s = s .. string.char(string.byte(strbuf, i + 1) ~ (box[(box[a] + box[j] - 2) % 256 + 1]))
end
if operation == 'DECODE' then
local time_check = tonumber(string.sub(s, 1, 10))
if time_check == 0 or os.difftime(os.time(), -time_check) > 0 and string.sub(s, 11, 26) == string.sub(md5(string.sub(s, 27)), 1, 16) then
s = string.sub(s, 27)
else
s = ''
end
else
s = base64_encode(s):gsub("=", "")
s = keyc .. s
end
return s
end
-- print(encrypt_decrypt("your_string", "ENCODE", "your_key", 3600))
-- print(encrypt_decrypt(result_from_above_call, "DECODE", "your_key", 0))