java使用HAMC签名加密调用第三方接口

java使用HAMC签名调用第三方接口

请求格式

POST

application/x-www-form-urlencoded

HAMC 签名

    /*
     * encryptText:加密文本
     * encryptKey: 秘钥
     */
    public String HmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception {
        String ENCODING = "UTF-8";
        String MAC_NAME = "HmacSHA1";
        byte[] data = encryptKey.getBytes(ENCODING);
        //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
        //生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance(MAC_NAME);
        //用给定密钥初始化 Mac 对象
        mac.init(secretKey);

        byte[] text = encryptText.getBytes(ENCODING);
        //完成 Mac 操作
        byte[] bytes = mac.doFinal(text);
        //转16位小写hex
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() < 2) {
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

调用第三方接口

    /*
     * result:参数
     * url: 第三方接口url
     */
     public String httpCallCmf(Map<String ,String> result, String url) {
        //1.构造HttpClient的实例
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setContentCharset("utf-8");
        //2.构造PostMethod的实例
        PostMethod postMethod = new PostMethod(url);
        //like12 add,20160511,中文转码 //在头文件中设置转码
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
		//3.传参
        NameValuePair[] data = { 
        		new NameValuePair("photo", result.get("photo")),
                new NameValuePair("sign",  result.get("sign")),
        };
        postMethod.setRequestBody(data);
        try {
            //4.执行postMethod,调用http接口
            httpClient.executeMethod(postMethod);//200
            //5.读取内容
            //方法2 InputStream转String模式
            InputStream inputStream = postMethod.getResponseBodyAsStream();
            String responseMsg = IOUtils.toString(inputStream, "utf-8");
            //打印
            System.out.println("responseMsg:" + responseMsg);
            JSONObject JSONObject1 = JSONObject.parseObject(responseMsg);
            //6.处理返回的内容
			String result_code = JSONObject1.getString("result_code");
            String error_msg = JSONObject1.getString("error_msg");
            System.out.println("result_code:" + result_code);
            System.out.println("error_msg:" + error_msg);
            .....
            return "success";
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //7.释放连接
            postMethod.releaseConnection();
        }
        return "fail";
    }

使用HttpURLConnection方式传参会导致签名验证失败

参考:Spirits、

posted @ 2021-04-30 17:26  PoetryAndYou  阅读(374)  评论(0编辑  收藏  举报