springboot RSA加密解密

1,825 阅读12分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第9天,点击查看活动详情

RSA加密解密

RSA是1977年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。当时他们三人都在麻省理工学院工作。RSA就是他们三人姓氏开头字母拼在一起组成的

RSA算法是最常用的非对称加密算法,它通常是先生成一对RSA密钥,其中之一是保密密钥(私钥),由用户保存;另一个为公开密钥(公钥),可对外公开

下面是百度百科上的算法描述:

image.png

springboot 具体实现

加密是指利用某个值(密钥)对明文的数据通过一定的算法变换加密(密文)数据的过程,它的逆向过程叫解密

package com.seven7m.utils;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.crypto.Cipher;

import com.seven7m.constant.ApiConstant;
import org.apache.commons.codec.binary.Base64;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.util.Base64Utils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.alibaba.fastjson.JSONObject;

/**
 *
 */
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";

   /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 2048;
//    private static final int MAX_DECRYPT_BLOCK = 128;
    //获得公钥字符串
    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 String 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();
        String base64Str = Base64Utils.encodeToString(encryptText);
        return base64Str;
    }
    
    public static String encrypt(String content, String publicKeyStr) throws Exception {
        // 获取私钥
        PublicKey publicKey = getPublicKey(publicKeyStr);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        // URLEncoder编码解决中文乱码问题
        byte[] data = URLEncoder.encode(content, ApiConstant.DEFAULT_CHARSET).getBytes(ApiConstant.DEFAULT_CHARSET);
        // 加密时超过117字节就报错。为此采用分段加密的办法来加密
        byte[] enBytes = null;
        for (int i = 0; i < data.length; i += 117) {
            // 注意要使用2的倍数,否则会出现加密后的内容再解密时为乱码
            byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i, i + 117));
            enBytes = ArrayUtils.addAll(enBytes, doFinal);
        }
        String base64Str = Base64Utils.encodeToString(enBytes);
        return base64Str;
    }
    public static String decrypt(String content, String privateKeyStr) throws Exception {
        byte[] encryptText = Base64Utils.decodeFromString(content);
        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;
//        String base64Str = Base64Utils.encodeToString(plainText);
//        return base64Str;
        return new String(plainText);
    }

 

    public static void main(String[] args) {
        extracted();
//

    }

    private static void extracted() {
        Map<String, Object> keyMap;
//        byte[] cipherText;
        String 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);


            System.out.println("私钥------------------");
            System.out.println(privateKey);

            System.out.println("==========开始加密==========");
//        String s = "{"msg":"成功","code":"000000","data":[{"ageCustId":"61000000000021","ageCustName":"产品超级机构001","city":"福州市","createTime":"20210730143806","custAddress":"中国福建省福州市台江区江滨中大道","custId":"60000000509004","custName":"马尾悠闲烧烤测试7","endTime":"23:59","latitude":"26.053699","logMerInfos":"/business/60000000509004/2021/08/02/20210802101227490588.jpg","logoMer":"/business/60000000509004/2021/08/02/20210802101223941134.jpg","logoMerDts":"/business/60000000509004/2021/08/02/20210802101225337950.jpg","longitude":"119.327316","manTran":"4000","merInfo":"300字","operId":"61000000000021","phone":"15544556655","province":"福建省","startTime":"00:00","status":"10A","syn":"0","typeId":"1","updateTime":"20210802101233","workDate":"1;4;5"},{"ageCustId":"61000000000021","ageCustName":"产品超级机构001","city":"福州市","createTime":"20210730143806","custAddress":"中国福建省福州市晋安区鼓山路","custId":"60000000513001","custName":"马尾悠闲烧烤测试8","endTime":"23:59","latitude":"26.040744","logoMer":"/business/60000000513001/2021/08/02/20210802101138468976.jpg","logoMerDts":"/business/60000000513001/2021/08/02/20210802101140698347.jpg;/business/60000000513001/2021/08/02/20210802101142802808.jpg","logoMerList":"/business/60000000513001/2021/08/02/20210802101143815364.jpg;/business/60000000513001/2021/08/02/20210802101145124517.jpg;/business/60000000513001/2021/08/02/20210802101146321068.jpg;","longitude":"119.386711","manTran":"100","merInfo":"啥啊 不需要介绍","operId":"61000000000021","phone":"18845645566","province":"福建省","startTime":"01:00","status":"10A","syn":"0","typeId":"1","updateTime":"20210802101159","workDate":"1;2"},{"ageCustId":"61000000000021","ageCustName":"产品超级机构001","city":"福州市","createTime":"20210730143807","custAddress":"中国福建省福州市马尾区儒江西路164-18号","custId":"60000000517002","custName":"马尾悠闲烧烤测试9","endTime":"23:59","latitude":"26.020691","logMerInfos":"/business/60000000517002/2021/07/30/20210730170206200271.jpg;/business/60000000517002/2021/07/30/20210730170209269093.jpg","logoMer":"/business/60000000517002/2021/07/30/20210730170141797551.jpg","logoMerDts":"/business/60000000517002/2021/07/30/20210730170143164442.jpg;/business/60000000517002/2021/07/30/20210730170146161524.jpg;/business/60000000517002/2021/07/30/20210730170148308827.jpg","logoMerList":"/business/60000000517002/2021/07/30/20210730170150873833.jpg;/business/60000000517002/2021/07/30/20210730170152767541.jpg;/business/60000000517002/2021/07/30/20210730170154542261.jpg;","longitude":"119.394608","manTran":"500","merInfo":"请不要输入!!!","operId":"61000000000021","phone":"18862662434","province":"福建省","startTime":"00:00","status":"10A","syn":"0","typeId":"1","updateTime":"20210802101106","workDate":"1;2;3;4;5;6;7"},{"ageCustId":"61000000000021","ageCustName":"产品超级机构001","createTime":"20210730143804","custId":"60000000499001","custName":"马尾悠闲烧烤测试6","operId":"61000000000021","status":"10A","syn":"0","typeId":"1","updateTime":"20210730143804"},{"ageCustId":"61000000000021","ageCustName":"产品超级机构001","createTime":"20210730143805","custId":"60000000500003","custName":"福建限公司","operId":"61000000000021","status":"10A","syn":"0","typeId":"4","updateTime":"20210730143805"},{"ageCustId":"6100000062","ageCustName":"产品超级机构0102","city":"天津市","createTime":"20210730102957","custAddress":"中国天津市天津市津南区睿泽道","custId":"60000000337006","custName":"福建国网科技有限公司","endTime":"23:59","latitude":"39.019184","logMerInfos":"/business/60000000337006/2021/07/30/20210730104033312936.jpg","logoMer":"/business/60000000337006/2021/07/30/20210730103933456553.jpg","logoMerDts":"/business/60000000337006/2021/07/30/20210730103935187964.jpg;/business/60000000337006/2021/07/30/20210730103937812174.jpg","logoMerList":"/business/60000000337006/2021/07/30/20210730104019836676.jpg;/business/60000000337006/2021/07/30/20210730104021858481.jpg;/business/60000000337006/2021/07/30/20210730104023846778.jpg;","longitude":"117.301025","manTran":"5000","merInfo":"介绍一下啊啊啊啊","operId":"61000000000021","phone":"13410081867","province":"天津","startTime":"21:00","status":"10A","syn":"0","typeId":"2","updateTime":"20210730104041","workDate":"6;7"},{"ageCustId":"6100000419","createTime":"20210730102958","custAddress":"中国江苏省南京市雨花台区铁心桥街道","custId":"60000000337007","custName":"福建国公司","endTime":"03:00","latitude":"31.929292","logoMer":"/business/60000000337007/2021/07/30/20210730104133892440.jpg","logoMerDts":"/business/60000000337007/2021/07/30/20210730104135712251.jpg","longitude":"118.763409","manTran":"4000","merInfo":"可介绍","operId":"61000000000021","phone":"15512341234","startTime":"01:00","status":"10X","syn":"0","updateTime":"20210730143557","workDate":"1"},{"ageCustId":"6100000491","createTime":"20210730103000","custAddress":"中国江苏省南京市玄武区玄武门街道","custId":"60000000337009","custName":"福建公司","endTime":"16:00","latitude":"32.071375","logMerInfos":"/business/60000000337009/2021/07/30/20210730103325859715.jpg","logoMer":"/business/60000000337009/2021/07/30/20210730103245221365.jpg","logoMerDts":"/business/60000000337009/2021/07/30/20210730103247931868.jpg;/business/60000000337009/2021/07/30/20210730103250947040.jpg;/business/60000000337009/2021/07/30/20210730103252547462.jpg","longitude":"118.794994","manTran":"3500","merInfo":"这又是一个客户介绍","operId":"61000000000021","phone":"18812344321","startTime":"01:00","status":"10X","syn":"0","updateTime":"20210730143552","workDate":"1;2;3;4;5"},{"ageCustId":"6100000492","createTime":"20210730103000","custAddress":"中国江苏省南京市栖霞区新尧路","custId":"60000000337010","custName":"福建限公司","endTime":"23:59","latitude":"32.125762","logoMer":"/business/60000000337010/2021/07/30/20210730104223385206.jpg","logoMerDts":"/business/60000000337010/2021/07/30/20210730104225499200.jpg","longitude":"118.875332","manTran":"10","merInfo":"简单介绍","operId":"61000000000021","phone":"12245645645","startTime":"00:00","status":"10X","syn":"0","updateTime":"20210730143554","workDate":"3;4"},{"ageCustId":"61000000000021","createTime":"20210730110640","custAddress":"中国云南省楚雄彝族自治州牟定县中园东路","custId":"60000000527002","custName":"云南澜岳知识产权服务有限责任公司","endTime":"23:59","latitude":"25.312218","logMerInfos":"/business/60000000527002/2021/07/30/20210730101747506081.jpg","logoMer":"/business/60000000527002/2021/07/30/20210730100101196109.jpg","logoMerDts":"/business/60000000527002/2021/07/30/20210730101735972730.jpg;/business/60000000527002/2021/07/30/20210730101739980308.jpg","longitude":"101.547489","manTran":"50","merInfo":"这是一个介绍","operId":"61000000000021","phone":"18862662434","startTime":"00:00","status":"10X","syn":"0","updateTime":"20210730143549","workDate":"1;2;3;4;5;6;7"}]}";
            input= "{"addvcd":"350000","time":"2022-03-10 00:27:42","stdata":[{"stcd":"41111154","stnm":"塔庙*","rvnm":"泥峪河","hnnm":"渭河","bsnm":"黄河","lgtd":107.999176,"lttd":34.11116,"stlc":"陕西省西安市","addvcd":"610124","dtmnm":"","dtmel":"","dtpr":"","sttp":"ZZ","frgrd":"5","esstym":"","bgfrym":"","atcunit":"","admauth":"陕西西安防汛","locality":"陕西水文","stbk":"","stazt":"","dstrvm":"","drna":"","phcd":"","usfl":"","comments":"","moditime":"2019-06-28 10:20:58"}]}";

            System.out.println("原字符串s = " + input);
            System.out.println("原字符串长度 = " + input.length());

            cipherText = encrypt(input.getBytes(), publicKey);
            //加密后的东西
            System.out.println("密文=======" + new String(cipherText));
            //开始解密
//            byte[] plainText = decrypt(cipherText, privateKey);
            String plainText = decrypt(cipherText, privateKey);
            System.out.println("解密后明文===== " + new String(plainText));
            System.out.println("验证签名-----------");

            TreeMap map = new TreeMap(new MComparator());
            map.put("age", 20);
            map.put("name", "张三");
            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;
    }

    static class MComparator implements Comparator {
        @Override
        public int compare(Object obj1, Object obj2) {
            String ele1 = (String) obj1;
            String ele2 = (String) obj2;
            return ele2.compareTo(ele1);
        }
    }

}

如果加密的数据长度较小,加密解密是没有问题的,但是数据比较大的时候解密就会出现下面异常

Data must not be longer than 117 bytes异常 RSA加密解密内容超长报错

也很好解决,将RSA最大解密密文大小改为128即可。

/**
     * RSA最大解密密文大小
     */
 //   private static final int MAX_DECRYPT_BLOCK = 2048;
    private static final int MAX_DECRYPT_BLOCK = 128;