在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
一)需求背景 --判断table是否为空 local function isTableEmpty(t) return t == nil or next(t) == nil end --两个table合并 local function union(table1,table2) for k,v in pairs(table2) do table1[k] = v end return table1 end --检验请求的sign签名是否正确 --params:传入的参数值组成的table --secret:项目secret,根据key找到secret local function signcheck(params,secret) --判断参数是否为空,为空报异常 if isTableEmpty(params) then local mess = "参数为空" ngx.log(ngx.ERR, mess) return false,mess end if secret == nil then local mess="私钥为空" ngx.log(ngx.ERR, mess) return false,mess end --平台分配给某客户端类型的keyID local key = params["key"]; if key == nil then local mess = "key值为空" ngx.log(ngx.ERR, mess) return false,mess end --判断是否有签名参数 local sign = params["sign"] if sign == nil then local mess="签名参数为空" ngx.log(ngx.ERR, mess) return false,mess end --是否存在时间戳的参数 local timestamp = params["time"] if timestamp == nil then local mess="时间戳参数为空" ngx.log(ngx.ERR, mess) return false,mess end --时间戳有没有过期,10秒过期 local now_mill = ngx.now() * 1000--毫秒级 if now_mill - timestamp > 30000 then local mess="链接过期" ngx.log(ngx.ERR, mess) return false,mess end local keys, tmp = {}, {} --提出所有的键名并按字符顺序排序 for k, _ in pairs(params) do if k ~= "sign" then keys[#keys+1] = k end end table.sort(keys) --根据排序好的键名依次读取值并拼接字符串成key=value&key=value for _,k in pairs(keys) do if type(params[k]) == "string" or type(params[k]) == "number" then tmp[#tmp+1] = k .. "=" .. tostring(params[k]) end end --将salt添加到最后,计算正确的签名sign值并与传入的sign签名对比, local signchar = table.concat(tmp, "&") .. "&" ..secret local rightsign = ngx.md5(signchar) if sign ~= rightsign then --如果签名错误返回错误信息并记录日志, --local mess="sign error: sign,"..sign.."right sign:"..rightsign.." sign_char:"..signchar local mess="sign error: sign,"..sign.."right sign:"..rightsign.." sign_char:"..table.concat(tmp, "&") ngx.log(ngx.ERR, mess) return false,mess end return true end local params = {} local get_args = ngx.req.get_uri_args(); ngx.req.read_body() local post_args = ngx.req.get_post_args(); union(params,get_args) union(params,post_args) --根据keyID到后台服务获取secret local secret = "abc123" local checkResult,mess = signcheck(params,secret) if not checkResult then ngx.say(mess); return ngx.exit(ngx.HTTP_FORBIDDEN) --直接返回403 end java代码,模仿请求 import java.io.IOException; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SignApplication { public static void main(String[] args) throws IOException { SpringApplication.run(SignApplication.class, args); HashMap<String,String> params = new HashMap<String,String>(); params.put("key", "1"); params.put("a", "1"); params.put("c", "w"); params.put("b", "2"); long time = new Date().getTime(); params.put("time", "" + time); System.out.println(time); String sign = getSignature(params,"123456"); System.out.println(sign); params.put("sign", sign); String resp = HttpUtil.doGet("http://10.11.0.215/sign",params); System.out.println(resp); } /** * 签名生成算法 * @param HashMap<String,String> params 请求参数集,所有参数必须已转换为字符串类型 * @param String secret 签名密钥 * @return 签名 * @throws IOException */ public static String getSignature(HashMap<String,String> params, String secret) throws IOException { // 先将参数以其参数名的字典序升序进行排序 Map<String, String> sortedParams = new TreeMap<String, String>(params); Set<Entry<String, String>> entrys = sortedParams.entrySet(); // 遍历排序后的字典,将所有参数按"key=value"格式拼接在一起 StringBuilder basestring = new StringBuilder(); for (Entry<String, String> param : entrys) { if(basestring.length() != 0){ basestring.append("&"); } basestring.append(param.getKey()).append("=").append(param.getValue()); } basestring.append("&"); basestring.append(secret); System.out.println("basestring="+basestring); // 使用MD5对待签名串求签 byte[] bytes = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); bytes = md5.digest(basestring.toString().getBytes("UTF-8")); } catch (GeneralSecurityException ex) { throw new IOException(ex); } String strSign = new String(bytes); System.out.println("strSign="+strSign); // 将MD5输出的二进制结果转换为小写的十六进制 StringBuilder sign = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(bytes[i] & 0xFF); if (hex.length() == 1) { sign.append("0"); } sign.append(hex); } return sign.toString(); } } python代码模仿请求 #coding=utf-8 import time import requests # 生成签名的字符串 def getSignature(params, secret): # basestring=a=1&b=hello&c=world&key=1&time=1566877802288 ivlist = [] # 拼凑字符串 for i,v in params.items(): tmpstr=str(i)+"="+str(v) ivlist.append(tmpstr) ivlist.append(secret) basestr = "&".join(ivlist) print("basestr = %s" % basestr) # 由于MD5模块在python3中被移除 # 在python3中使用hashlib模块进行md5操作 import hashlib # 创建md5对象 m = hashlib.md5() # 此处必须encode,若写法为m.update(str) 报错为: Unicode-objects must be encoded before hashing # 因为python3里默认的str是unicode # 或者 b = bytes(str, encoding='utf-8'),作用相同,都是encode为bytes b = basestr.encode(encoding='utf-8') m.update(b) str_md5 = m.hexdigest() return str_md5 if __name__ == "__main__": # 拼凑访问url params = {"a":22,"b":"hello","c":"wrold","key":1} time = int(round(time.time() * 1000)) params["time"] = time sinstr = getSignature(params, "abc123") print(sinstr) params["sign"] = sinstr url = "http://10.11.0.215/sign?a=1&b=hello&c=world&key=1&time={time}&sign={sign}".format(time = time, sign = sinstr) print("url = %s" % url) # 模拟正确的请求 res = requests.get("http://10.11.0.215/sign", params = params, timeout=10) res.encoding="utf-8" print(res.content)
|
请发表评论