Java http 加签(验签)工具类:采用SHA-1算法

Java http 加签(验签)工具类:采用SHA-1算法

什么是加签验签

加签验签,发送消息方,对消息加签名;接受消息方,验证签名是否正确。

为什么要做加签验签

做加签验签的目的主要目的就是,验证消息的完整性

如何做加签验签

简单来说,
发送消息方:
1、根据消息内容形成摘要
2、根据摘要形成签名字段
3、发送消息
接受消息方:
1、接受消息
2、根据消息内容形成摘要
3、根据摘要去验证签名是否正确

加签验签具体作用说明,可以自行搜索这里只是简单描述,而且加签验签的方式也有很多种,本文章仅供参考

加签规则

加签规则:
涉及参数:
nonce:随机串;
timestamp:时间戳;
body:post请求的参数json串
secretKey:秘钥;
(秘钥:a8f0eca7bb2511e8ada152543a77b4af 随机)
signature:加签串;

参数的话可以根据场景需要,自己加一些,比如 xx渠道专用字段:privatefield: 111000 固定码

加签规则:nonce, timestamp,secretKey、body(post的参数json串)三个字段进行字典排序后,采用SHA-1算法获取并得到signature

具体代码(可以直接Ctrl C+V)

本工具使用采用SHA-1算法 ,仅供参考,简单方便,不要刨根问底(因为本人没研究过签名算法代码片.

package com.xxxx.channel.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;


public class Sha1SignUtil {

    public static String sign(Map<String,Object> maps) throws Exception{
        //获取信息摘要 - 参数字典排序后字符串
        String decrypt = getOrderByLexicographic(maps);
        try {
            //指定sha1算法
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(decrypt.getBytes());
            //获取字节数组
            byte[] messageDigest = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString().toLowerCase();

        } catch (NoSuchAlgorithmException e) {
            throw new DigestException("签名错误!");
        }
    }

    /**
     * 获取参数的字典排序
     * @param maps 参数key-value map集合
     * @return String 排序后的字符串
     */
    private static String getOrderByLexicographic(Map<String,Object> maps){
        return splitParams(lexicographicOrder(getParamsName(maps)),maps);
    }
    /**
     * 获取参数名称 key
     * @param maps 参数key-value map集合
     * @return
     */
    private static List<String> getParamsName(Map<String,Object> maps){
        List<String> values = new ArrayList<String>();
        for(Map.Entry<String,Object> entry : maps.entrySet()){
            if(entry.getValue() != null){
                values.add(entry.getValue().toString());
            }
        }
        return values;
    }
    /**
     * 参数名称按字典排序
     * @param paramNames 参数名称List集合
     * @return 排序后的参数名称List集合
     */
    private static List<String> lexicographicOrder(List<String> paramNames){
        Collections.sort(paramNames);
        return paramNames;
    }
    /**
     * 拼接排序好的参数名称和参数值
     * @param paramNames 排序后的参数名称集合
     * @param maps 参数key-value map集合
     * @return String 拼接后的字符串
     */
    private static String splitParams(List<String> paramNames,Map<String,Object> maps){
        StringBuilder paramStr = new StringBuilder();
        for(String paramName : paramNames){
            paramStr.append(String.valueOf(paramName));
        }
        return paramStr.toString();
    }

    public static void main(String[]args) throws Exception{

        String nonce = RandomStringUtils.randomAlphanumeric(16);
        String timestamp = String.valueOf(System.currentTimeMillis());
        String secretKey="a8f0eca7bb2511e8ada152543a77b4af";

        HashMap signMap = new HashMap<>( );
        signMap.put("nonce", nonce);
        signMap.put("timestamp", timestamp);
        signMap.put("secretKey",secretKey);
        //具体post请求参数 使用map填充
        HashMap mapWb = new HashMap();
        mapWb.put("name","张三");//姓名
        mapWb.put("age",24);//年龄
        mapWb.put("phoneNumber", "13910010002");//手机号码

        String params=new Gson().toJson(mapWb);
        signMap.put("data", params);
        System.out.println( "==调用接口生成签名使用参数=={}"+new Gson().toJson(signMap));
        String sign = Sha1SignUtil.sign(signMap);
        System.out.println( "==生成签名==" + sign);

        //因为生成签名和验证签名 需要双方约定使用同一套工具 所以过程是一致的这里展示生成签名 显得有点多余;
        Boolean check = checkSign(mapWb,secretKey,nonce,timestamp,sign);
        if(check){
            //打印出这一行就是胜利
            System.out.println( "验证成功 sign:" + sign);
        }

    }

    //验证签名
    private static Boolean checkSign(Object body, String secretKey, String nonce, String timestamp, String sign) {
        // 创建一个不进行HtmlEscaping的Gson对象
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String params= gson.toJson(body);

        //验证签名
        Map<String, Object> signMap = new HashMap<String, Object>();
        signMap.put("nonce", nonce);
        signMap.put("timestamp", timestamp);
        signMap.put("secretKey", secretKey);
        signMap.put("data",params);
        String sign2 = null;
        try {
            sign2 = Sha1SignUtil.sign(signMap);
            if (sign.equals(sign2)){
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}

感谢查看,记得点赞哦 ~ ~

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值