Openresty: AES encrypt and decrypt
location ~ /api/aes { set $string $http_string; set $encoded $http_encoded; add_header 'Content-Type' 'text/plain'; content_by_lua_block { local aes = require "resty.aes" local str = require "resty.string" local aes_128_cbc_with_iv = aes:new("1234567890123456", nil, aes.cipher(128,"cbc"), {iv="1234567890123456"}) local function GET(value) local args = ngx.req.get_uri_args() local v = nil for key, val in pairs(args) do if key == value then if type(val) == "table" then v = table.concat(val, ", ") else v = val end break end end return v end local function convertAscii(value) return value:gsub("(..)",function(c)return c.char(tonumber(c,16))end) end local function all_trim(s) return s:match( "^%s*(.-)%s*$" ) end local string = GET("string") local encoded = GET("encoded") if string == nil then string = ngx.var.string end if encoded == nil then encoded = ngx.var.encoded end if string ~= "" then local encrypted = aes_128_cbc_with_iv:encrypt(all_trim(string)) ngx.say( str.to_hex(encrypted) ) elseif encoded ~= "" then local encrypted = aes_128_cbc_with_iv:decrypt(convertAscii(encoded)) ngx.say( all_trim(encrypted) ) end } }
Demo encrypt: http://162.250.190.40/api/aes?string=123456
CURL:
curl -sk --url http://162.250.190.40/api/aes --header "string: 123456"
Result: d637735ae9e21ba50cb686b74fab8d2c
Demo decrypt: http://162.250.190.40/api/aes?encoded=d637735ae9e21ba50cb686b74fab8d2c
CURL:
curl -sk --url http://162.250.190.40/api/aes --header "encoded: d637735ae9e21ba50cb686b74fab8d2c"
Result: 123456