欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java Http接口加签、验签操作方法

程序员文章站 2024-03-09 16:03:53
1、业务背景 最近接触了一些电商业务,发现在处理电商业务接口时,比如淘宝、支付类接口,接口双方为了确保数据参数在传输过程中未经过篡改,都需要对接口数据进行加签,然后在接...

1、业务背景

最近接触了一些电商业务,发现在处理电商业务接口时,比如淘宝、支付类接口,接口双方为了确保数据参数在传输过程中未经过篡改,都需要对接口数据进行加签,然后在接口服务器端对接口参数进行验签,确保两个签名是一样的,验签通过之后再进行业务逻辑处理。我们这里主要介绍一下处理思路,至于签名算法我不做过多介绍,网上一大堆。

2、处理思路

双方约定好,参数按特定顺序排列,比如按首字母的顺序排列,如url:http://xxx/xxx.do?a=wersd&b=sd2354&c=4&signature=xxxxxxxxxxxx(signature为传入的签名),等你拿到入参后,将参数串a=wersd&b=sd2354&c=4按你们约定的签名规则,自己用md5加签一次,然后和入参的signature值对比,以确认调用者是否合法,这就是接口签名验证的思路。

3、实例练习

接口双方经过沟通,对接口达成如下共识:

1、注意事项,主要指接口的的协议、传入参数类型、签名算法、文件格式等说明

Java Http接口加签、验签操作方法

2、下面是一个电商业务接口的真实案例,双方约定好了接口url、业务参数、固定参数、签名以及返回数据格式

Java Http接口加签、验签操作方法

Java Http接口加签、验签操作方法

接口调用时,接口调用方代码如下(仅供参考):
package com.pcmall;

import java.io.bufferedreader;					
import java.io.dataoutputstream;					
import java.io.ioexception;					
import java.io.inputstreamreader;					
import java.io.unsupportedencodingexception;					
import java.net.httpurlconnection;					
import java.net.url;					
import java.net.urlencoder;					
import java.security.messagedigest;					
import java.security.nosuchalgorithmexception;					
import java.util.arraylist;					
import java.util.collections;					
import java.util.iterator;					
import java.util.list;					
import java.util.map;					
import java.util.treemap;
					
public class apitest {					
  static string test_url = "待定";					
  static string test_key = "待定";					
  static string test_sec = "待定";					
  					
  public static void main(string[] args) throws unsupportedencodingexception, nosuchalgorithmexception {					
    string result = getresult(test_url, getreqparam());					
    system.out.print(result);					
  }					
					
  private static string getreqparam() throws unsupportedencodingexception, nosuchalgorithmexception {					
  	treemap<string, string> req = new treemap<string, string>();			
    req.put("a", test_key);					
    req.put("f", "json");					
    req.put("l", "zh_cn");					
    req.put("m", "zhongan.repair.query");					
    req.put("v", "1.0");					
    req.put("i", "" + system.currenttimemillis() / 1000);					
    req.put("params", "{\"assignno\":\"test018\"}");					
    req.put("s", sign(req, null, test_sec));					
    					
    stringbuilder param = new stringbuilder();					
    for (iterator<map.entry<string, string>> it = req.entryset().iterator(); it.hasnext();) {					
      map.entry<string, string> e = it.next();					
      param.append("&").append(e.getkey()).append("=").append(urlencoder.encode(e.getvalue(), "utf-8"));					
    }					
    					
    return param.tostring().substring(1);					
  }					
  					
  private static string sign(map<string, string> paramvalues, list<string> ignoreparamnames, string secret) throws nosuchalgorithmexception, unsupportedencodingexception {					
    stringbuilder sb = new stringbuilder();					
    list<string> paramnames = new arraylist<string>(paramvalues.size());					
    paramnames.addall(paramvalues.keyset());					
    if (ignoreparamnames != null && ignoreparamnames.size() > 0) {					
      for (string ignoreparamname : ignoreparamnames) {					
        paramnames.remove(ignoreparamname);					
      }					
    }					
    collections.sort(paramnames);					
    					
    sb.append(secret);					
    for (string paramname : paramnames) {					
      sb.append(paramname).append(paramvalues.get(paramname));					
    }					
    sb.append(secret);					
					
    messagedigest md = messagedigest.getinstance("sha-1");					
    return byte2hex(md.digest(sb.tostring().getbytes("utf-8")));					
  }					
  					
  private static string byte2hex(byte[] bytes) {					
    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.touppercase());					
    }					
    return sign.tostring();					
  }					
  					
  private static string getresult(string urlstr, string content) {					
    url url = null;					
    httpurlconnection connection = null;					
    try {					
      url = new url(urlstr);					
      connection = (httpurlconnection) url.openconnection();					
      connection.setdooutput(true);					
      connection.setdoinput(true);					
      connection.setrequestmethod("post");					
      connection.setrequestproperty("content-type", "application/x-www-form-urlencoded;charset=utf-8");					
      connection.setusecaches(false);					
      connection.connect();					
      					
      dataoutputstream out = new dataoutputstream(connection.getoutputstream());					
      out.write(content.getbytes("utf-8"));					
      out.flush();					
      out.close();					
      					
      bufferedreader reader = new bufferedreader(new inputstreamreader(connection.getinputstream(), "utf-8"));					
      stringbuffer buffer = new stringbuffer();					
      string line = "";					
      while ((line = reader.readline()) != null) {					
        buffer.append(line);					
      }					
      reader.close();					
					
      return buffer.tostring();					
    } catch (ioexception e) {					
      e.printstacktrace();					
    } finally {					
      if (connection != null) {					
        connection.disconnect();					
      }					
    }					
    					
    return null;					
  }	
  
  
}

服务器端代码如下(仅供参考):

@requestmapping("/repairtakeorder")
	@responsebody
	public responsevo repairtakeorder(@requestbody string jsonstr) {
		logger.info("repairtakeorder入参:" + jsonstr);

		responsevo responsevo = null;
		try {
			repairorder repairorder = jackjsonutil.tobean(jsonstr,
					repairorder.class);
			treemap<string, string> paramsmap = new treemap<string, string>();
			paramsmap.put("gsxx01", repairorder.getgsxx01());
			paramsmap.put("ordertype", repairorder.getordertype().tostring());
			paramsmap.put("serviceno", repairorder.getserviceno());
			paramsmap.put("vipcard", repairorder.getvipcard());
			paramsmap.put("customername", repairorder.getcustomername());
			paramsmap.put("customerphone", repairorder.getcustomerphone());
			paramsmap.put("customertel", repairorder.getcustomertel());
			paramsmap.put("province", repairorder.getprovince());
			paramsmap.put("city", repairorder.getcity());
			paramsmap.put("county", repairorder.getcounty());
			paramsmap.put("address", repairorder.getaddress());
			paramsmap.put("salercode", repairorder.getsalercode());
			paramsmap.put("salername", repairorder.getsalername());
			paramsmap.put("storecode", repairorder.getstorecode());
			paramsmap.put("storename", repairorder.getstorename());
			paramsmap.put("site", repairorder.getsite());

			paramsmap.put("sitedesp", repairorder.getsitedesp());
			paramsmap.put("engineercode", repairorder.getengineercode());
			paramsmap.put("engineername", repairorder.getengineername());
			if (repairorder.getservicedate() != null) {
				paramsmap.put("servicedate",
						dateutils.formatdate(repairorder.getservicedate()));
			}

			if (repairorder.getsaleprice() != null) {
				paramsmap.put("saleprice", repairorder.getsaleprice()
						.tostring());
			}

			paramsmap.put("profitcenter", repairorder.getprofitcenter());
			paramsmap.put("costcenter", repairorder.getcostcenter());
			paramsmap.put("gsxx02", repairorder.getgsxx02());
			paramsmap.put("returnreason", repairorder.getreturnreason());
			if (repairorder.getoriorder() != null) {
				paramsmap.put("oriorder", repairorder.getoriorder().tostring());
			}

			if (repairorder.getoriserviceno() != null) {
				paramsmap.put("oriserviceno", repairorder.getoriserviceno());
			}

			// 拼接签名原串(a=1&b=2)
			string paramsrc = requestutils.getparamsrc(paramsmap);
			logger.info("签名原串:" + paramsrc);
			//进行验签操作
			if (signutils.verifymd5(paramsrc, repairorder.getsign())) {
				//处理业务逻辑
				responsevo=erpserviceimpl.repairtakeorder(repairorder);
				
			} else {
				responsevo = new responsevo();
				responsevo.setsuccess(false);
				responsevo.seterrormsg("验签失败");
			}

		} catch (exception e) {
			logger.error("", e);
			responsevo = new responsevo();
			responsevo.setsuccess(false);
			responsevo.seterrormsg(stringutils.isnotblank(e.getmessage()) ? e.getmessage() : "后台异常");
		}
		return responsevo;

	}

以上这篇java http接口加签、验签操作方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。