wuxw před 4 roky
rodič
revize
410ddd29a7

+ 238 - 0
service-api/src/main/java/com/java110/api/smo/payment/adapt/plutuspay/PlutusOweFeeToNotifyAdapt.java

@@ -0,0 +1,238 @@
+/*
+ * Copyright 2017-2020 吴学文 and java110 team.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.java110.api.smo.payment.adapt.plutuspay;
+
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.java110.api.properties.WechatAuthProperties;
+import com.java110.api.smo.DefaultAbstractComponentSMO;
+import com.java110.api.smo.payment.adapt.IOweFeeToNotifyAdapt;
+import com.java110.core.factory.WechatFactory;
+import com.java110.dto.fee.FeeDto;
+import com.java110.dto.smallWeChat.SmallWeChatDto;
+import com.java110.utils.cache.CommonCache;
+import com.java110.utils.constant.CommonConstant;
+import com.java110.utils.util.BeanConvertUtil;
+import com.java110.utils.util.DateUtil;
+import com.java110.utils.util.PayUtil;
+import com.java110.utils.util.StringUtil;
+import org.apache.commons.codec.digest.DigestUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Component;
+import org.springframework.web.client.RestTemplate;
+
+import java.io.UnsupportedEncodingException;
+import java.util.*;
+
+/**
+ * 富友 支付 通知实现
+ * 说明:信息通过 http 或 https 形式 post 请求递交给前置系统,编码必须为 UTF-8
+ * Json 格式参数名:如下表
+ * 参数值:如下表
+ * 测试地址:商户提供
+ * 生产地址:待定
+ * <p>
+ * 如图中第 6 步中异步回调,下单(主扫)交易的结果是以异步的形式进行回调的。富友在接受到支付宝等支付通道的回调结果以
+ * 后再回调商户。商户接收回调成功处理成功后返回字符串”1” , 后富友停止回调给商户。最多回调 5 次,每次间隔 30S。
+ * (重要~重要~重要:不保证通知最终一定能成功,在订单状态不明或者没有收到微信,支付结果通知的情况下,
+ * 建议商户主动调用【2.3 订单查询】确认订单状态)
+ * 只有主扫、公众号/服务窗支付会通过此接口发异步通知,条码支付没有异步通知。
+ *
+ * @desc add by 吴学文 15:33
+ */
+
+@Component(value = "plutusOweFeeToNotifyAdapt")
+public class PlutusOweFeeToNotifyAdapt extends DefaultAbstractComponentSMO implements IOweFeeToNotifyAdapt {
+
+    private static final Logger logger = LoggerFactory.getLogger(PlutusOweFeeToNotifyAdapt.class);
+
+    private static final String APP_ID = "992020011134400001";
+
+    @Autowired
+    private RestTemplate restTemplate;
+
+    @Autowired
+    private WechatAuthProperties wechatAuthProperties;
+
+    /**
+     * 预下单
+     *
+     * @param param
+     * @return
+     * @throws Exception
+     */
+    public String confirmPayFee(String param, String wId) {
+        JSONObject resJson = new JSONObject();
+        resJson.put("errCode", "INTERNAL_ERROR");
+        resJson.put("errMsg", "失败");
+        try {
+            JSONObject map = JSONObject.parseObject(param);
+            logger.info("【银联支付回调】 回调数据: \n" + map);
+            //更新数据
+            int result = confirmPayFee(map, wId);
+            if (result > 0) {
+                //支付成功
+                resJson.put("errCode", "SUCCESS");
+                resJson.put("errMsg", "成功");
+            }
+        } catch (Exception e) {
+            logger.error("通知失败", e);
+            resJson.put("result_msg", "鉴权失败");
+        }
+
+        return resJson.toJSONString();
+    }
+
+
+    public int confirmPayFee(JSONObject map, String wId) {
+        wId = wId.replace(" ", "+");
+        ResponseEntity<String> responseEntity = null;
+
+        String appId = WechatFactory.getAppId(wId);
+        SmallWeChatDto smallWeChatDto = getSmallWechat(appId);
+
+        if (smallWeChatDto == null) { //从配置文件中获取 小程序配置信息
+            smallWeChatDto = new SmallWeChatDto();
+            smallWeChatDto.setAppId(wechatAuthProperties.getAppId());
+            smallWeChatDto.setAppSecret(wechatAuthProperties.getSecret());
+            smallWeChatDto.setMchId(wechatAuthProperties.getMchId());
+            smallWeChatDto.setPayPassword(wechatAuthProperties.getKey());
+        }
+        SortedMap<String, String> paramMap = new TreeMap<String, String>();
+        for (String key : map.keySet()) {
+            if ("wId".equals(key)) {
+                continue;
+            }
+            paramMap.put(key, map.get(key).toString());
+        }
+        String preSign = map.getString("preSign");
+        String text = preSign + smallWeChatDto.getPayPassword();
+        System.out.println("待签名字符串:" + text);
+        String sign = DigestUtils.sha256Hex(getContentBytes(text)).toUpperCase();
+
+        if (!sign.equals(map.get("sign"))) {
+            throw new IllegalArgumentException("鉴权失败");
+        }
+//        JSONObject billPayment = JSONObject.parseObject(map.getString("billPayment"));
+//        String orderId = billPayment.get("merOrderId").toString().substring(4);
+        String outTradeNo = map.get("merOrderId").toString();
+        String orderId = outTradeNo.substring(4);
+        String order = CommonCache.getAndRemoveValue(FeeDto.REDIS_PAY_OWE_FEE + orderId);
+
+        if (StringUtil.isEmpty(order)) {
+            return 1;// 说明已经处理过了 再不处理
+        }
+
+        //查询用户ID
+        JSONObject paramIn = JSONObject.parseObject(order);
+        paramIn.put("oId", orderId);
+        freshFees(paramIn);
+        String url = "fee.payOweFee";
+        responseEntity = this.callCenterService(getHeaders("-1"), paramIn.toJSONString(), url, HttpMethod.POST);
+
+        if (responseEntity.getStatusCode() != HttpStatus.OK) {
+            return 0;
+        }
+        return 1;
+    }
+
+
+    private void freshFees(JSONObject paramIn) {
+        if (!paramIn.containsKey("fees")) {
+            return;
+        }
+
+        JSONArray fees = paramIn.getJSONArray("fees");
+        JSONObject fee = null;
+        for (int feeIndex = 0; feeIndex < fees.size(); feeIndex++) {
+            fee = fees.getJSONObject(feeIndex);
+            if (fee.containsKey("deadlineTime")) {
+                fee.put("startTime", fee.getString("endTime"));
+                fee.put("endTime", fee.getString("deadlineTime"));
+                fee.put("receivedAmount", fee.getString("feePrice"));
+                fee.put("state", "");
+            }
+        }
+    }
+
+
+    private Map<String, String> getHeaders(String userId) {
+        Map<String, String> headers = new HashMap<>();
+        headers.put(CommonConstant.HTTP_APP_ID.toLowerCase(), APP_ID);
+        headers.put(CommonConstant.HTTP_USER_ID.toLowerCase(), userId);
+        headers.put(CommonConstant.HTTP_TRANSACTION_ID.toLowerCase(), UUID.randomUUID().toString());
+        headers.put(CommonConstant.HTTP_REQ_TIME.toLowerCase(), DateUtil.getDefaultFormateTimeString(new Date()));
+        headers.put(CommonConstant.HTTP_SIGN.toLowerCase(), "");
+        return headers;
+    }
+
+
+    private SmallWeChatDto getSmallWechat(String appId) {
+
+        ResponseEntity responseEntity = null;
+
+        responseEntity = this.callCenterService(getHeaders("-1"), "",
+                "smallWeChat.listSmallWeChats?appId="
+                        + appId + "&page=1&row=1", HttpMethod.GET);
+
+        if (responseEntity.getStatusCode() != HttpStatus.OK) {
+            return null;
+        }
+        JSONObject smallWechatObj = JSONObject.parseObject(responseEntity.getBody().toString());
+        JSONArray smallWeChats = smallWechatObj.getJSONArray("smallWeChats");
+
+        if (smallWeChats == null || smallWeChats.size() < 1) {
+            return null;
+        }
+
+        return BeanConvertUtil.covertBean(smallWeChats.get(0), SmallWeChatDto.class);
+    }
+
+    /**
+     * 富友 生成sign 方法
+     *
+     * @param paramMap
+     * @param payPassword
+     * @return
+     */
+    private String createSign(JSONObject paramMap, String payPassword) {
+        String str = paramMap.getString("mchnt_cd") + "|"
+                + paramMap.getString("mchnt_order_no") + "|"
+                + paramMap.getString("settle_order_amt") + "|"
+                + paramMap.getString("order_amt") + "|"
+                + paramMap.getString("txn_fin_ts") + "|"
+                + paramMap.getString("reserved_fy_settle_dt") + "|"
+                + paramMap.getString("random_str") + "|"
+                + payPassword;
+        return PayUtil.md5(str);
+    }
+
+
+    // 根据编码类型获得签名内容byte[]
+    public static byte[] getContentBytes(String content) {
+        try {
+            return content.getBytes("UTF-8");
+        } catch (UnsupportedEncodingException e) {
+            throw new RuntimeException("签名过程中出现错误");
+        }
+    }
+
+}

+ 193 - 0
service-api/src/main/java/com/java110/api/smo/payment/adapt/plutuspay/PlutusPayAdapt.java

@@ -0,0 +1,193 @@
+/*
+ * Copyright 2017-2020 吴学文 and java110 team.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.java110.api.smo.payment.adapt.plutuspay;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.java110.api.properties.WechatAuthProperties;
+import com.java110.api.smo.payment.adapt.IPayAdapt;
+import com.java110.core.factory.ChinaUmsFactory;
+import com.java110.core.factory.WechatFactory;
+import com.java110.dto.smallWeChat.SmallWeChatDto;
+import com.java110.utils.cache.MappingCache;
+import com.java110.utils.constant.WechatConstant;
+import com.java110.utils.util.DateUtil;
+import com.java110.utils.util.PayUtil;
+import com.java110.utils.util.StringUtil;
+import org.bouncycastle.util.encoders.Base64;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.*;
+import org.springframework.stereotype.Component;
+import org.springframework.web.client.RestTemplate;
+
+import java.util.Map;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+/**
+ * http://open.plutuspay.com/index.html
+ *
+ * @desc add by 吴学文 15:33
+ */
+
+@Component(value = "plutusPayAdapt")
+public class PlutusPayAdapt implements IPayAdapt {
+    private static final Logger logger = LoggerFactory.getLogger(PlutusPayAdapt.class);
+
+    //微信支付
+    public static final String PAY_UNIFIED_ORDER_URL = "https://api.plutuspay.com/open/v2/jsPay";
+
+
+    private static final String VERSION = "1.0";
+
+    @Autowired
+    private WechatAuthProperties wechatAuthProperties;
+
+    /**
+     * 预下单
+     *
+     * @param orderNum
+     * @param money
+     * @param openId
+     * @return
+     * @throws Exception
+     */
+    public Map<String, String> java110Payment(RestTemplate outRestTemplate,
+                                              String feeName, String tradeType,
+                                              String orderNum, double money,
+                                              String openId, SmallWeChatDto smallWeChatDto) throws Exception {
+        return java110Payment(outRestTemplate, feeName, tradeType, orderNum, money, openId, smallWeChatDto, "");
+    }
+
+    /**
+     * 预下单
+     *
+     * @param orderNum
+     * @param money
+     * @param openId
+     * @return
+     * @throws Exception
+     */
+    public Map<String, String> java110Payment(RestTemplate outRestTemplate,
+                                              String feeName, String tradeType,
+                                              String orderNum, double money,
+                                              String openId, SmallWeChatDto smallWeChatDto, String notifyUrl) throws Exception {
+        logger.info("【小程序支付】 统一下单开始, 订单编号=" + orderNum);
+        SortedMap<String, String> resultMap = new TreeMap<String, String>();
+        //生成支付金额,开发环境处理支付金额数到0.01、0.02、0.03元
+        double payAmount = PayUtil.getPayAmountByEnv(MappingCache.getValue("HC_ENV"), money);
+        //添加或更新支付记录(参数跟进自己业务需求添加)
+
+        JSONObject resMap = null;
+
+        if (StringUtil.isEmpty(notifyUrl)) {
+            resMap = this.java110UnifieldOrder(outRestTemplate, feeName, orderNum, tradeType, payAmount, openId, smallWeChatDto);
+        } else {
+            resMap = this.java110UnifieldOrder(outRestTemplate, feeName, orderNum, tradeType, payAmount, openId, smallWeChatDto, notifyUrl);
+        }
+
+            if (WechatAuthProperties.TRADE_TYPE_JSAPI.equals(tradeType)) {
+                resultMap.putAll(JSONObject.toJavaObject(resMap, Map.class));
+                resultMap.put("sign",resultMap.get("paySign"));
+            } else if (WechatAuthProperties.TRADE_TYPE_APP.equals(tradeType)) {
+                resultMap.put("appId", smallWeChatDto.getAppId());
+                resultMap.put("timeStamp", PayUtil.getCurrentTimeStamp());
+                resultMap.put("nonceStr", PayUtil.makeUUID(32));
+                resultMap.put("partnerid", smallWeChatDto.getMchId());
+                resultMap.put("prepayid", resMap.getString("session_id"));
+                //resultMap.put("signType", "MD5");
+                resultMap.put("sign", PayUtil.createSign(resultMap, smallWeChatDto.getPayPassword()));
+            } else if (WechatAuthProperties.TRADE_TYPE_NATIVE.equals(tradeType)) {
+                resultMap.put("prepayId", resMap.getString("session_id"));
+                resultMap.put("codeUrl", resMap.getString("qr_code"));
+            }
+            resultMap.put("code", "0");
+            resultMap.put("msg", "下单成功");
+            logger.info("【小程序支付】统一下单成功,返回参数:" + resultMap);
+//        } else {
+//            resultMap.put("code", resMap.getString("errCode"));
+//            resultMap.put("msg", resMap.getString("errMsg"));
+//            logger.info("【小程序支付】统一下单失败,失败原因:" + resMap.get("errMsg"));
+//        }
+        return resultMap;
+    }
+
+    /**
+     * 小程序支付统一下单
+     */
+    private JSONObject java110UnifieldOrder(RestTemplate outRestTemplate, String feeName, String orderNum,
+                                            String tradeType, double payAmount, String openid,
+                                            SmallWeChatDto smallWeChatDto) throws Exception {
+        return java110UnifieldOrder(outRestTemplate, feeName, orderNum, tradeType, payAmount, openid, smallWeChatDto, wechatAuthProperties.getWxNotifyUrl());
+    }
+
+    /**
+     * 小程序支付统一下单
+     */
+    private JSONObject java110UnifieldOrder(RestTemplate outRestTemplate, String feeName, String orderNum,
+                                            String tradeType, double payAmount, String openid,
+                                            SmallWeChatDto smallWeChatDto, String notifyUrl) throws Exception {
+
+        String systemName = MappingCache.getValue(WechatConstant.WECHAT_DOMAIN, WechatConstant.PAY_GOOD_NAME);
+
+        JSONObject paramMap = new JSONObject();
+
+        paramMap.put("appId", smallWeChatDto.getAppId());
+        paramMap.put("openId", openid);
+        paramMap.put("sn", smallWeChatDto.getMchId()); // 富友分配给二级商户的商户号
+        paramMap.put("outTradeId", orderNum);
+        paramMap.put("tradeAmount", PayUtil.moneyToIntegerStr(payAmount));
+        paramMap.put("payTypeId", "1003");
+        paramMap.put("notifyUrl", notifyUrl + "?wId=" + WechatFactory.getWId(smallWeChatDto.getAppId()));
+
+        logger.debug("调用支付统一下单接口" + paramMap.toJSONString());
+
+        String param = PlutusUtil.Encryption(paramMap.toJSONString());
+        System.out.println(param);
+
+        String str = PlutusUtil.post(wechatAuthProperties.getWxPayUnifiedOrder(), param);
+        System.out.println(str);
+
+        JSONObject json = JSON.parseObject(str);
+
+        String signature = json.getString("signature");
+        String content = json.getString("content");
+
+        //验签
+        Boolean verify = PlutusUtil.verify256(content, Base64.decode(signature));
+        //验签成功
+        if (!verify) {
+            throw new IllegalArgumentException("支付失败签名失败");
+        }
+            //解密
+            byte[] bb = PlutusUtil.decrypt(Base64.decode(content), PlutusUtil.SECRET_KEY);
+            //服务器返回内容
+            String paramOut =  new String(bb);
+
+          JSONObject paramObj =   JSONObject.parseObject(paramOut);
+        logger.debug("统一下单返回" + paramOut);
+
+        if (paramObj.getString("paramObj") != "00") {
+            throw new IllegalArgumentException("支付失败"+paramObj.getString("error"));
+        }
+
+        return paramObj.getJSONObject("payInfo");
+    }
+
+
+}

Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 239 - 0
service-api/src/main/java/com/java110/api/smo/payment/adapt/plutuspay/PlutusPayNotifyAdapt.java


+ 251 - 0
service-api/src/main/java/com/java110/api/smo/payment/adapt/plutuspay/PlutusUtil.java

@@ -0,0 +1,251 @@
+package com.java110.api.smo.payment.adapt.plutuspay;
+
+import com.alibaba.fastjson.JSONObject;
+import org.bouncycastle.util.encoders.Base64;
+
+import javax.crypto.Cipher;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+import java.io.BufferedInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+import java.io.UnsupportedEncodingException;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.security.*;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+
+
+/**
+ * AES加密解密算法
+ *
+ * @author long
+ */
+public class PlutusUtil {
+    // /** 算法/模式/填充 **/
+    private static final String CipherMode = "AES/CBC/PKCS5Padding";
+
+    private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
+
+    //密钥
+    public static String SECRET_KEY = "3738597658384d6c316a4758527a5a35";
+
+
+    // /** 创建密钥 **/
+    private static SecretKeySpec createKey(String key) {
+        byte[] data = null;
+        data = hexStringToByteArray(key);
+        return new SecretKeySpec(data, "AES");
+    }
+
+    /**
+     * 实例化私钥
+     *
+     * @return
+     */
+    private static PrivateKey getPrivateKey() {
+        PrivateKey privateKey = null;
+        String priKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDKO3fVJVtKuBlj\n" +
+                "T2HkhjQykS/jKiNuQ4o0IItGJwTv4IX7m+vlKwqPQFylr1POdRX0z4lwFWRWvxCv\n" +
+                "fpORW83W6a6J6LSKfDc5g5h0mhnYdYMdzLawVEM1YqJD5EVRQZHKleMvwkZbLWt0\n" +
+                "bFJ2o4uVDO7bs/ABv6UdAmOlP6K2fUcw14r5nF+sUpXw9v2wCQys3k3djGOQJQFX\n" +
+                "7/aADXsROp0xPFhHVgu18Rtjp7y5ib8bQ1obMmlf+4yThjlAMJQN9sBTOByUXLQw\n" +
+                "VCCL5oYsSs318mnJnTSmkK88pxDYp1Y2K7WQDbZtFiDbNA4bqCecQGbX+6c7NWSr\n" +
+                "dWMn0BsfAgMBAAECggEBAJXh1UKH2U1bfJV59Bemz3Da4h7+0BucuwU/SXnI2YPf\n" +
+                "Z+2+9ep3J/Bbx06UzwwpAwjZ+Aa2FBOmr/shWMVWwQwTTWSwr34j6doaiheBTr56\n" +
+                "+Z5QZuXwzY73d0PSHv3GFwOKa0KuPe69jvJOhh+fvofNegojJjJlkz4Y0zlaHIIa\n" +
+                "ri5iuKM2b5sSeoohCwJF9vmkje9UUpzYgIQhiiLe7jHIj6PP+ILA/+J0IqlqZg7Z\n" +
+                "nZIClUfy1Bn533yxCHvvM2V1gkT4zsmLtgIsJrGP3FHKW0yGj2JKaxI8T4JtjYCX\n" +
+                "QhXoYkzjr+111udD8oe0Tg/8PquFvqi5Cq0rkDqNwsECgYEA5ENMeAuENaG1TKov\n" +
+                "rpXUhmrB1tOcp/BvOLq4KIsgY6/4k2q4MbpK3qXeY90YlLaEsggD8eiEG3RNmGNR\n" +
+                "IbmnqyQBQyk+KYCMTGBTRGqwwjJjTDBkV0hOeLV8CBBcAFGKXLf15HyhuG4xRhvu\n" +
+                "Sq8YcIbvA9fSLkaaYY/pyuoQA3kCgYEA4s5r20Na9WQ5M3QLRY5HMlUb0E0SMSEd\n" +
+                "4UF6mgzpdafDWSsvcOSnJguahZ25DJk12ptKKaJPXxPEa2+u0FN/Jv9KDPkXggXS\n" +
+                "z6yS9E1HfFSbRK6An1Q+34vDahrU5lTJQ7eKYDzb2Xm1gI1VxrxdAN5+Bk3IvH1T\n" +
+                "FUowLOFGFVcCgYAYwqgX2X/05V6qO0fC02PjVM9EA15Z5T3bVH3HgBf6WEtJimkC\n" +
+                "k+etMSbnhEM3Vnkcarwq0IMMC1ijcBqL4vyqFtTAOUgR7mzJmCVQJZaY6ihVSmaI\n" +
+                "BULl2yHiKgwgyLeOiTH2IALW47UamssFdOrcwfZJX27gMC5s6NR+e1dTWQKBgFMu\n" +
+                "qdgM5/s/+sqoMMod2HbZSA4pdhaWssK+pRyCx8zi7n5xnECnW7ZUYyPGKOw59Mps\n" +
+                "UdLbOIkCUvOkTlURinze/GWtpbWGNT79aBg5j5JF5XxXE81btIOAWvc7SAIB7p7r\n" +
+                "XdDWATvNq4euTltJEkMTVt0xAgI/ZI1WXDzZkj6ZAoGBANTu3Ko+x8OgH3WdMSxD\n" +
+                "YTersdTb4j2bj3IkZF8xJemyO7qerEK6H9mkGjSZlR17bQeE3b0RF97GgIw/fIZX\n" +
+                "o6oE7re3EaCp6/PIXTzTPRlLTPNlBvFqDrNurM0YndjAgANa1tDDQ12W8Vtjvv8g\n" +
+                "mX7PvHOnfws522nLZHBz+SzT";
+
+        try {
+
+            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(priKey.getBytes()));
+            KeyFactory keyf = KeyFactory.getInstance("RSA");
+            privateKey = keyf.generatePrivate(priPKCS8);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return privateKey;
+    }
+
+
+    //实例化公钥
+    public static PublicKey getPublicKey() {
+        PublicKey publicKey = null;
+        String pubKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsIvJ1y1G7/BaWqcq/qVc\n" +
+                "6u7nQb7nuH9vI2MoJc2H9ZGVD27oOIPkEDy7kIiteIaq5lrj6Z8VpG4n84MycsC7\n" +
+                "/7AVScV238pdBkQM/vtm6j3jJsh7dcAU/ngMTzusUgFKlUhClR4uztQM+/obIcAl\n" +
+                "wDlGnY/Nw5XbmzE6igcLgAZLkYq54hfJSG7EyctonL8Q8SPn51eEy9TMh3jju/RH\n" +
+                "KeZzpJ5mYTFzqGU798rzv6r9uBKC/lZvuQcQwK7li4ctINA3EPmRbiLwzLZnTZBf\n" +
+                "h7AmtTMqM2NYrn6Co23NQYLdg0WPSPv1Sxj69BSJ1q62boT2gOO3rsxaK8FN3EJb\n" +
+                "sQIDAQAB";
+
+        try {
+            X509EncodedKeySpec PubKeySpec = new X509EncodedKeySpec(
+                    Base64.decode(pubKey.getBytes()));
+            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
+            // 取公钥匙对象
+            publicKey = keyFactory.generatePublic(PubKeySpec);
+        } catch (NoSuchAlgorithmException e1) {
+            e1.printStackTrace();
+        } catch (InvalidKeySpecException e1) {
+            e1.printStackTrace();
+        }
+        return publicKey;
+    }
+
+
+    // /** 加密字节数据 **/
+    public static byte[] encrypt(byte[] content, String password) {
+        try {
+            byte[] data = hexStringToByteArray(password);
+            SecretKeySpec key = new SecretKeySpec(data, "AES");
+            Cipher cipher = Cipher.getInstance(CipherMode);
+            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
+            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(new byte[16]));
+            byte[] result = cipher.doFinal(content);
+            return result;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+
+    /**
+     * 解密AES加密过的字符串
+     *
+     * @param content  AES加密过过的内容
+     * @param password 加密时的密码
+     * @return 明文
+     */
+    public static byte[] decrypt(byte[] content, String password) {
+        try {
+            byte[] data = hexStringToByteArray(password);
+            SecretKeySpec key = new SecretKeySpec(data, "AES");
+            Cipher cipher = Cipher.getInstance(CipherMode);
+            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[16]));
+            byte[] result = cipher.doFinal(content);
+            return result;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    public static String Encryption(String url) {
+        JSONObject object = new JSONObject();
+        try {
+            byte[] b = url.getBytes("UTF-8");
+            //AES加密
+            byte[] text = PlutusUtil.encrypt(b, SECRET_KEY);
+            String content = Base64.toBase64String(text);
+
+            //签名
+            byte[] sign = PlutusUtil.sign256(text, getPrivateKey());
+            String signature = Base64.toBase64String(sign);
+
+            object.put("devId", "xqHQzM5n");
+            object.put("content", content);
+            object.put("signature", signature);
+
+        } catch (UnsupportedEncodingException e) {
+            e.printStackTrace();
+        }
+        return object.toString();
+    }
+
+
+    public static byte[] hexStringToByteArray(String s) {
+        int len = s.length();
+        byte[] b = new byte[len / 2];
+        for (int i = 0; i < len; i += 2) {
+            // 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个字节
+            b[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
+                    .digit(s.charAt(i + 1), 16));
+        }
+        return b;
+    }
+
+    //SHA256withRSA签名
+    public static byte[] sign256(byte[] data, PrivateKey privateKey) {
+        byte[] signed = null;
+        Signature signature = null;
+        try {
+            signature = Signature.getInstance(SIGNATURE_ALGORITHM);
+            signature.initSign(privateKey);
+            signature.update(data);
+            signed = signature.sign();
+        } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
+            e.printStackTrace();
+        }
+        return signed;
+    }
+
+
+    //SHA256withRSA验签
+    public static boolean verify256(String data, byte[] sign) {
+        if (data == null || sign == null) {
+            return false;
+        }
+        try {
+            Signature signetcheck = Signature.getInstance(SIGNATURE_ALGORITHM);
+            signetcheck.initVerify(getPublicKey());
+            signetcheck.update(Base64.decode(data));
+            return signetcheck.verify(sign);
+        } catch (Exception e) {
+            return false;
+        }
+    }
+
+    public static String post(String path,String post){
+        URL url = null;
+        try {
+            url = new URL(path);
+            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
+            httpURLConnection.setRequestMethod("POST");// 提交模式
+            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
+            httpURLConnection.setReadTimeout(15000);//读取超时 单位毫秒
+            // 发送POST请求必须设置如下两行
+            httpURLConnection.setDoOutput(true);
+            httpURLConnection.setDoInput(true);
+            // 获取URLConnection对象对应的输出流
+            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
+            // 发送请求参数
+            printWriter.write(post);//post的参数 xx=xx&yy=yy
+            // flush输出流的缓冲
+            printWriter.flush();
+            //开始获取数据
+            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
+            ByteArrayOutputStream bos = new ByteArrayOutputStream();
+            int len;
+            byte[] arr = new byte[1024];
+            while((len=bis.read(arr))!= -1){
+                bos.write(arr,0,len);
+                bos.flush();
+            }
+            bos.close();
+            return bos.toString();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return "请求失败";
+    }
+}