springboot 签名验证

简介: springboot 签名验证

签名过程(对post方法的body进行签名):

  • 发送者通过私钥privateKey对数据进行加签,得到签名串sign
  • 发送者将sign和数据一起包装成json格式发送给接收方
TreeMap map = new TreeMap(new MComparator());
            map.put("jag", 234);
            map.put("jay", 3344);
            String str = JSONObject.toJSONString(map);
            System.out.println("\n原文:" + str);
            byte[] signature = sign(str.getBytes(), privateKey);
            String sign = Base64.encodeBase64String(signature);

验签过程:

  • 接受者通过公钥publicKey对数据进行验签
  • 签名的验签和加签通过多种加密算法实现
byte[] bodyBytes = StreamUtils.copyToByteArray(httpServletRequest.getInputStream());
            String body = new String(bodyBytes, httpServletRequest.getCharacterEncoding());
            logger.info("请求体:{}", body);
//        Map<String, Object> map = JSON.parseObject(body,Map.class);
            Map<String, Object> map = JsonUtil.jsonToMap(body);
            String signStr = String.valueOf(map.get("sign"));
            byte[] sign = org.apache.commons.codec.binary.Base64.decodeBase64(signStr);
            map.remove("sign");
            Set set = map.keySet();
            Iterator it = set.iterator();
            TreeMap tm = new TreeMap(new RSAUtil.MComparator());
            while (it.hasNext()) {
                String key = String.valueOf(it.next());
                tm.put(key, map.get(key));
            }
            Map<String, Object> keyMap = RSAUtil.initKey();
            String publicKey = RSAUtil.publicKey;
            String mapSortStr = JSONObject.toJSONString(tm);
            logger.info("传过来的字符串:mapSortStr:{}", mapSortStr);
            //公钥验证
            boolean flagB = RSAUtil.verify(mapSortStr.getBytes(), sign, publicKey);

工具类参考

public class RSAUtil {
    public static final String KEY_ALGORITHM = "RSA";
    public static final String PUBLIC_KEY = "RSAPublicKey";
    public static final String PRIVATE_KEY = "RSAPrivateKey";
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
    public static String publicKey = "xxx";
    public static String privateKey = "xxx";
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;
    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 2048;
    //获得公钥字符串
    public static String getPublicKeyStr(Map<String, Object> keyMap) throws Exception {
        //获得map中的公钥对象 转为key对象
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        //编码返回字符串
        return encryptBASE64(key.getEncoded());
    }
    //获得私钥字符串
    public static String getPrivateKeyStr(Map<String, Object> keyMap) throws Exception {
        //获得map中的私钥对象 转为key对象
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        //编码返回字符串
        return encryptBASE64(key.getEncoded());
    }
    //获取公钥
    public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = (new BASE64Decoder()).decodeBuffer(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }
    //获取私钥
    public static PrivateKey getPrivateKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = (new BASE64Decoder()).decodeBuffer(key);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }
    //解码返回byte
    public static byte[] decryptBASE64(String key) throws Exception {
        return (new BASE64Decoder()).decodeBuffer(key);
    }
    //编码返回字符串
    public static String encryptBASE64(byte[] key) throws Exception {
        return (new BASE64Encoder()).encodeBuffer(key);
    }
    //***************************签名和验证*******************************
    public static byte[] sign(byte[] data, String privateKeyStr) throws Exception {
        PrivateKey priK = getPrivateKey(privateKeyStr);
        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initSign(priK);
        sig.update(data);
        return sig.sign();
    }
    // 验签
    public static boolean verify(byte[] data, byte[] sign, String publicKeyStr) throws Exception {
        PublicKey pubK = getPublicKey(publicKeyStr);
        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initVerify(pubK);
        sig.update(data);
        return sig.verify(sign);
    }
    //************************加密解密**************************
    public static byte[] encrypt(byte[] plainText, String publicKeyStr) throws Exception {
        PublicKey publicKey = getPublicKey(publicKeyStr);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = plainText.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        int i = 0;
        byte[] cache;
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(plainText, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(plainText, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptText = out.toByteArray();
        out.close();
        return encryptText;
    }
    public static byte[] decrypt(byte[] encryptText, String privateKeyStr) throws Exception {
        PrivateKey privateKey = getPrivateKey(privateKeyStr);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        int inputLen = encryptText.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptText, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptText, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] plainText = out.toByteArray();
        out.close();
        return plainText;
    }
    public static void main(String[] args) {
        Map<String, Object> keyMap;
        byte[] cipherText;
        String input = "Hello World!";
        try {
            keyMap = initKey();
            //String publicKey = getPublicKeyStr(keyMap);
            System.out.println("公钥------------------");
            System.out.println(publicKey);
            //String privateKey = getPrivateKeyStr(keyMap);
            System.out.println("私钥------------------");
            System.out.println(privateKey);
            System.out.println("测试可行性-------------------");
            System.out.println("明文=======" + input);
            cipherText = encrypt(input.getBytes(), publicKey);
            //加密后的东西
            System.out.println("密文=======" + new String(cipherText));
            //开始解密
            byte[] plainText = decrypt(cipherText, privateKey);
            System.out.println("解密后明文===== " + new String(plainText));
            System.out.println("验证签名-----------");
            TreeMap map = new TreeMap(new MComparator());
            map.put("jag", 234);
            map.put("jay", 3344);
            String str = JSONObject.toJSONString(map);
            System.out.println("\n原文:" + str);
            byte[] signature = sign(str.getBytes(), privateKey);
            System.out.println(Base64.encodeBase64String(signature));
            boolean status = verify(str.getBytes(), signature, publicKey);
            System.out.println("验证情况:" + status);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Map<String, Object> initKey() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator
                .getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<String, Object>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }
    public static class MComparator implements Comparator {
        public int compare(Object obj1, Object obj2) {
            String ele1 = (String) obj1;
            String ele2 = (String) obj2;
            return ele2.compareTo(ele1);
        }
    }
}

Base64Util 主要用于传输内容加解密用

package com.sinochemitech.util;
import org.apache.commons.codec.binary.Base64;
public class Base64Util{
    /**
     * Decoding to binary
     * @param base64 base64
     * @return byte
     * @throws Exception Exception
     */
    public static byte[] decode(String base64) throws Exception {
        return Base64.decodeBase64(base64);
    }
    /**
     * Binary encoding as a string
     * @param bytes byte
     * @return String
     * @throws Exception Exception
     */
    public static String encode(byte[] bytes) throws Exception {
        return new String(Base64.encodeBase64(bytes));
    }
}

文章持续更新,可以关注下方公众号或者微信搜一搜「 最后一支迷迭香 」第一时间阅读,获取更完整的链路资料。

相关实践学习
基于阿里云DeepGPU实例,用AI画唯美国风少女
本实验基于阿里云DeepGPU实例,使用aiacctorch加速stable-diffusion-webui,用AI画唯美国风少女,可提升性能至高至原性能的2.6倍。
相关文章
|
2月前
|
前端开发 安全 Java
SpringBoot验证框架@Valid
SpringBoot验证框架@Valid
48 1
|
2月前
|
JSON 前端开发 Java
SpringBoot 的优雅的接口参数验证
1. 为什么需要参数验证 在应用程序的开发中,我们经常会遇到需要保证传入参数的正确性的情况。例如,当我们在注册用户时,需要验证用户填写的表单数据是否符合规范,是否缺少必填字段,或者格式是否正确,等等。如果不对参数进行验证,我们的应用程序可能会因此受到攻击或者运行出错。 为了保证参数的正确性,我们需要使用参数验证机制,来检测并处理传入的参数格式是否符合规范。 2. 如何进行参数验证 Spring Boot内置了一个很强大的参数验证框架——JSR 303 Bean Validation 标准,它可以对我们的实体类参数进行校验,并且可以给我们提供详细的错误提示信息。
83 1
|
17天前
|
算法 Java API
在Spring Boot中实现接口签名验证通常涉及以下步骤
在Spring Boot中实现接口签名验证通常涉及以下步骤
40 4
|
2月前
|
Java 数据安全/隐私保护 开发者
SpringBoot整合TrueLicense生成和验证License证书
TrueLicense生成和验证License证书
|
2月前
|
JSON Java 数据格式
springboot全局异常实现以及@Valid和@Validated优雅实现入参验证
springboot全局异常实现以及@Valid和@Validated优雅实现入参验证
161 0
|
2月前
|
缓存 NoSQL Java
springboot集成图片验证+redis缓存一步到位2
springboot集成图片验证+redis缓存一步到位2
|
2月前
|
缓存 NoSQL Java
springboot集成图片验证+redis缓存一步到位
springboot集成图片验证+redis缓存一步到位
|
2月前
|
Java 数据格式 Spring
SpringBoot统一功能处理(统⼀⽤户登录权限验证、统⼀异常处理、统⼀数据格式封装)
SpringBoot统一功能处理(统⼀⽤户登录权限验证、统⼀异常处理、统⼀数据格式封装)
|
2月前
|
SQL 前端开发 Java
Hasor【环境搭建 01】SpringBoot集成Dataway接口配置服务(依赖+配置+数据库数据源初始化+注解添加+demo验证测试)
Hasor【环境搭建 01】SpringBoot集成Dataway接口配置服务(依赖+配置+数据库数据源初始化+注解添加+demo验证测试)
114 0
|
1天前
|
JavaScript Java 测试技术
基于SpringBoot+Vue的学生成绩管理系统的详细设计和实现(源码+lw+部署文档+讲解等)
基于SpringBoot+Vue的学生成绩管理系统的详细设计和实现(源码+lw+部署文档+讲解等)
16 0