通过RSA加密算法对入参进行分段加解密1

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Security;

/**
 * @author lianJiaYu
 * @date 2021/8/2 15:21
 */
public class Test2 {
    private static String filePath = "C:/Users/admin/Desktop/RSA/";
    private static String rsa_public_key = "rsa_public_key.txt";
    private static String rsa_private_key = "rsa_private_key.txt";
    public static void main(String[] args) throws Exception {
        //1、生成公钥和私钥
        //generateKeyPair();

        //2、进行测试
        String param = "{\n" +
                "\t\"appId\": \"100057\",\n" +
                "\t\"doMainName\": [\n" +
                "\t\t\"http://test-duanlian.4007222999.mobi/\"\n" +
                "\t]\n" +
                "}";
        //通过公钥来进行加密
        String encrypt = encrypt(param, rsa_public_key);
        //通过私钥进行解密
        String decrypt = decrypt(encrypt, rsa_private_key);
        System.out.println("加密前的参数:" + param);
        System.out.println("加密后的参数为:" + encrypt);
        System.out.println("解密后的参数:" + decrypt);

    }

    private static void generateKeyPair() throws Exception {
        Security.addProvider(new com.sun.crypto.provider.SunJCE());
        /** RSA算法要求有一个可信任的随机数源 */
        SecureRandom sr = new SecureRandom();
        /** 为RSA算法创建一个KeyPairGenerator对象 */

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
        kpg.initialize(4096, sr);
        /** 生成密匙对 */
        KeyPair kp = kpg.generateKeyPair();
        /** 得到公钥 */
        Key publicKey = kp.getPublic();
        /** 得到私钥 */
        Key privateKey = kp.getPrivate();
        System.out.println(publicKey.toString());
        System.out.println(privateKey.toString());

        //判断当前目录是否存在 不存在则创建
        creatFile(filePath);

        /** 用对象流将生成的密钥写入文件 */
        ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream(filePath+rsa_public_key));
        ObjectOutputStream oos2 = new ObjectOutputStream(new FileOutputStream(filePath+rsa_private_key));
        oos1.writeObject(publicKey);
        oos2.writeObject(privateKey);
        /** 清空缓存,关闭文件输出流 */
        oos1.close();
        oos2.close();
    }


    public static String encrypt(String source, String publickey) throws Exception {   //source为需要加密的对应  publickey-rsa公钥
        Resource resource = new ClassPathResource("/" + publickey);
        /** 将文件中的公钥对象读出 */
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(resource.getFile().getPath()));
        Key key = (Key) ois.readObject();
        ois.close();
        /** 得到Cipher对象来实现对源数据的RSA加密 */
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] b = source.getBytes("utf-8");

        byte[] b1 = null;
        /** 执行加密操作 */
        for (int i = 0; i < b.length; i += 501) {
            byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(b, i, i + 501));
            b1 = ArrayUtils.addAll(b1, doFinal);
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(b1);

    }

    public static String decrypt(String cryptograph, String privatekey) throws Exception { //cryptograph-通过rsa公钥加密得到的参数  privatekey-与公钥对应的私钥
        Resource resource = new ClassPathResource("/" + privatekey);
        /** 将文件中的私钥对象读出 */
        // cryptograph= new String(cryptograph.getBytes(),"gbk");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(resource.getFile().getPath()));
        Key key = (Key) ois.readObject();
        /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, key);
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b1 = decoder.decodeBuffer(cryptograph);
        /** 执行解密操作 */
        byte[] b = null;

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < b1.length; i += 512) {
            byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(b1, i, i + 512));
            sb.append(new String(doFinal, "utf-8"));
        }
        return sb.toString();

    }

    private static void creatFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
    }
}

生成的公钥和私钥默认放到resource目录下面 (不能修改编码 否则读文件的时候会报错 默认编码为ANSI)

posted @ 2021-08-05 14:35  难忘是想起  阅读(0)  评论(0)    收藏  举报  来源