2018年(273)
分类: 大数据
2018-06-22 14:59:33
/**
* generate signature by code, the algorithm is as follows:
* 1.sort the http params, if you use java, you can easily use treeMap data structure
* 2.join the param k-v
* 3.use hmac-sha1 encrypt the specified string
*
* @param params request params
* @param secret auth secret
* @return secret sign
* @throws Exception exception
*/ public static String generateSignature(Map params, String secret) throws Exception { final StringBuilder paramStr = new StringBuilder(); final Map sortedMap = new TreeMap<>(params); for (Map.Entry entry : sortedMap.entrySet()) {
paramStr.append(entry.getKey());
paramStr.append(entry.getValue());
}
Mac hmac = Mac.getInstance("HmacSHA1");
SecretKeySpec sec = new SecretKeySpec(secret.getBytes(), "HmacSHA1");
hmac.init(sec); byte[] digest = hmac.doFinal(paramStr.toString().getBytes()); return new String(new Hex().encode(digest), "UTF-8");
}
上文方法用于根据参数生成签名,注释中详细描述了签名算法的实现步骤,这其实就是过度描述代码明显细节
/**
* generate signature by params and secret, used for computing signature for http request.
*
* @param params request params
* @param secret auth secret
* @return secret sign
* @throws Exception exception
*/ public static String generateSignature(Map params, String secret) throws Exception { final StringBuilder paramStr = new StringBuilder(); final Map sortedMap = new TreeMap<>(params); for (Map.Entry entry : sortedMap.entrySet()) {
paramStr.append(entry.getKey());
paramStr.append(entry.getValue());
}
Mac hmac = Mac.getInstance("HmacSHA1");
SecretKeySpec sec = new SecretKeySpec(secret.getBytes(), "HmacSHA1");
hmac.init(sec); byte[] digest = hmac.doFinal(paramStr.toString().getBytes()); return new String(new Hex().encode(digest), "UTF-8");
}