栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

签名测试数据

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

签名测试数据

测试案例
```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.*;



//@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 getData() {
       Map map =new HashMap<>();
       Map 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 getOrderData(){
              String time=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date());
        Map 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.*;


public class RSAUtils {

    
    private static final String KEY_ALGORITHM = "RSA";
    
    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";

    public static final String PUBLIC_KEY = "RSAPublicKey";

    public static final String PRIVATE_KEY = "RSAPrivateKey";

    
    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);
    }

    
    public static String sign(Map params, String privateKey) throws Exception {
        String content = createLinkString(paramsFilter(params));
        return RSAUtils.sign(content, privateKey);
    }

    
    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));
    }

    
    public static boolean verify(Map params, String sign, String publicKey) throws Exception {
        String content = createLinkString(paramsFilter(params));
        return RSAUtils.verify(content, sign, publicKey);
    }


    
    public static Map 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 keyMap = new HashMap<>();
        keyMap.put(PUBLIC_KEY, Base64.encodeBase64String(publicKey.getEncoded()));
        keyMap.put(PRIVATE_KEY, Base64.encodeBase64String(privateKey.getEncoded()));
        return keyMap;
    }

    
    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;
    }

    
    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;
    }

    
    public static Map paramsFilter(Map 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;
        }
    }

    
    public static String createLinkString(Map 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;
    }

    
    public static String createSignString(Map params) {
        return createLinkString(paramsFilter(params));
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/932689.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号