签名测试数据

测试案例
```java

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.centerm.ydt.Application;
import com.centerm.ydt.dao.entity.SignatureBase;
import com.centerm.ydt.utils.IDUtils;
import com.centerm.ydt.utils.RSAUtils;
import lombok.extern.slf4j.Slf4j;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author wuqingxiang
 * @description
 * @since 2022/5/20 13:04
 */
//@SpringBootTest(classes=Application.class)
//@RunWith(SpringRunner.class)
@Slf4j
public class OrderControllerTest {

    private String privateKey="";
    private String host="";


    @Test
    public void createOrderTest(){

        String res=doPost(host+"order/add",new JSONObject(getData()).toString());
        System.out.println(res);
    }

    public String doPost(String url ,String json) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String res = "";

        try {
            HttpPost post = new HttpPost(url);
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            post.setEntity(entity);
            response = httpClient.execute(post);

            res = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res;
    }
    private   Map<String,Object> getData() {
       Map<String,Object> map =new HashMap<>();
       Map<String,String> order=getOrderData();
       String timestamp=System.currentTimeMillis()/1000+"";
       map.put("timestamp",timestamp);
       map.put("app_key","zgrs");
       map.put("content",order);

       order.put("timestamp",timestamp);
       order.put("app_key","zgrs");
      try{
          map.put("signature",RSAUtils.sign(order,privateKey));
      }catch(Exception e){
          log.error("签名错误",e.getMessage());
      }

        return map;
    }

    private String getRand(int rand){
        return new Random().nextInt(rand)+"";
    }
    private Map<String, String> getOrderData(){
              String time=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date());
        Map<String,String> map =new HashMap<>();
               
                map.put("id","111111111111");//订单id不能为空
                return map;
    }
}

加密工具


```java
package com.centerm.ydt.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;

/**
 * <p>rsa工具类</p>
 * <p>Created by qrf on 2019/5/30.</p>
 */
public class RSAUtils {

    /**
     * rsa算法
     */
    private static final String KEY_ALGORITHM = "RSA";
    /**
     * rsa前面算法
     */
    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";

    public static final String PUBLIC_KEY = "RSAPublicKey";

    public static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * rsa签名
     *
     * @param content
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String sign(String content, String privateKey) throws Exception {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        KeyFactory keyf = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);

        Signature signature = Signature.getInstance(SIGN_ALGORITHMS);

        signature.initSign(priKey);
        signature.update(content.getBytes());

        byte[] signed = signature.sign();

        return Base64.encodeBase64String(signed);
    }

    /**
     * rsa签名
     *
     * @param params
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String sign(Map<String, String> params, String privateKey) throws Exception {
        String content = createLinkString(paramsFilter(params));
        return RSAUtils.sign(content, privateKey);
    }

    /**
     * rsa验证签名
     *
     * @param content
     * @param sign
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static boolean verify(String content, String sign, String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        byte[] encodedKey = Base64.decodeBase64(publicKey);
        PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
        Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
        signature.initVerify(pubKey);
        signature.update(content.getBytes());
        return signature.verify(Base64.decodeBase64(sign));
    }

    /**
     * rsa验签
     *
     * @param params
     * @param sign
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static boolean verify(Map<String, String> params, String sign, String publicKey) throws Exception {
        String content = createLinkString(paramsFilter(params));
        return RSAUtils.verify(content, sign, publicKey);
    }


    /**
     * 生成rsa公私钥对
     *
     * @return
     * @throws Exception
     */
    public static Map<String, String> initKey() throws Exception {
        //获得对象 KeyPairGenerator 参数 RSA 1024个字节
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        //通过对象 KeyPairGenerator 获取对象KeyPair
        KeyPair keyPair = keyPairGen.generateKeyPair();

        //通过对象 KeyPair 获取RSA公私钥对象RSAPublicKey RSAPrivateKey
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        //公私钥对象存入map中
        Map<String, String> keyMap = new HashMap<>();
        keyMap.put(PUBLIC_KEY, Base64.encodeBase64String(publicKey.getEncoded()));
        keyMap.put(PRIVATE_KEY, Base64.encodeBase64String(privateKey.getEncoded()));
        return keyMap;
    }

    /**
     * rsa加密
     *
     * @param str
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static String encrypt(String str, String publicKey) throws Exception {
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }

    /**
     * rsa解密
     *
     * @param str
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String str, String privateKey) throws Exception {
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }

    /**
     * 参数过滤
     *
     * @param params 参数
     * @return 过滤参数
     */
    public static Map<String, String> paramsFilter(Map<String, String> params) {
        HashMap result = new HashMap();
        if (params != null && params.size() > 0) {
            Iterator i$ = params.keySet().iterator();

            while (i$.hasNext()) {
                String key = (String) i$.next();
                String value = (String) params.get(key);
                if (value != null && !value.equals("") && !key.equalsIgnoreCase("sign")) {
                    result.put(key, value);
                }
            }

            return result;
        } else {
            return result;
        }
    }

    /**
     * 拼接字符
     *
     * @param params 参数
     * @return 拼接字符
     */
    public static String createLinkString(Map<String, String> params) {
        ArrayList keys = new ArrayList(params.keySet());
        Collections.sort(keys);
        String prestr = "";

        for (int i = 0; i < keys.size(); ++i) {
            String key = (String) keys.get(i);
            String value = (String) params.get(key);
            prestr = prestr + key + "=" + value + "&";
        }

        if (prestr.length() > 1) {
            prestr = prestr.substring(0, prestr.length() - 1);
        }

        return prestr;
    }

    /**
     * 拼接用于签名的字符串
     *
     * @param params 参数
     * @return
     */
    public static String createSignString(Map<String, String> params) {
        return createLinkString(paramsFilter(params));
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值