Java代码实现RSA算法加密解密文件功能

一、概述

底层算法不做赘述,想要了解自行百度。
RSA属于非对称加密,非对称加密有公钥和私钥两个概念,私钥自己拥有,不能给别人,公钥公开。根据应用的不同,我们可以选择使用不同的密钥加密:

  1. 签名:使用私钥加密,公钥解密。用于让所有公钥所有者验证私钥所有者的身份并且用来防止私钥所有者发布的内容被篡改,但是不用来保证内容不被他人获得。
  2. 加密:用公钥加密,私钥解密。用于向公钥所有者发布信息,这个信息可能被他人篡改,但是无法被他人获得。

二、详细代码

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class test1 {

    /** RSA 算法 */
    private static final String RSA = "RSA";
    /** BC 提供 */
    private static final String BC = "BC";
    /** UTF-8 编码 */
    private static final String UTF8 = "UTF-8";
    /** 公钥默认读取路径 */
    private static final String PUBLIC_KEY_FILE = "D:/RSA/" + "request.key";
    /** 私钥默认读取路径 */
    private static final String PRIVATE_KEY_FILE = "D:/RSA/" + "response.key";
    /** 私钥 */
    private static String prky;
    /** 公钥 */
    private static String puky;
    /** 读取文件,以 1M 为单位 */
    private static final Integer READER_1M = (2<<9) * 1;

    // 加密等级制度
    // - 等级越高,加密越严格(前提是保护要私钥且不能丢失)
    // - 个人电脑加密等级,不要超出 S3072
    // - 加密等级越高,速度越慢。
    // - 推荐使用 S1024(速度较快) 或 S2048(相比较而言更安全)
    // - S3072(速度太慢),其余更高等级加密不推荐

    private static Size S1024;
    private static Size S2048;
    private static Size S3072;
    private static Size S7680;
    private static Size S15360;

    /** 当前加密等级 */
    private static Size thisSize;

    static {

        // 初始化加密等级
        S1024 = Size.create(2 * (2 << 8));
        S2048 = Size.create(4 * (2 << 8));
        S3072 = Size.create(6 * (2 << 8));
        S7680 = Size.create(15 * (2 << 8));
        S15360 = Size.create(30 * (2 << 8));

        // 加密等级通过修改 thisSize 来指定
        thisSize = S1024 ;
    }

    public static void main(String[] args) {
        // 1、生成密钥对文件,并保存;如果存在,则不生成
        createKey();

        // 2、加载密钥
        readKeyPair();

        // 注:如果密钥一直变,可以执行一次,把密钥拿出来直接放配置文件中,之后直接读取使用就行,1 2 步就可以省了

        // 3、加密操作
        // 将 公钥字符串 加载为 公钥对象
        RSAPublicKey rsaPublicKey = (RSAPublicKey) loadPublicKey(puky);
        // 读取文件转byte数组, 如果文件是前端传过来的,接收是用 MultipartFile 类型接收,转byte数组之直接 multipartFile.getBytes()
        File file1 = new File("D:\\RSA\\RSA测试专用.zip");
        byte[] sourceData = handleReadData(file1);
        // 使用公钥进行加密数据
        byte[] pukyData = encryptByPublicKey(sourceData, rsaPublicKey.getEncoded());
        // 创建文件
        File pukyfile = new File("D:\\RSA\\RSA测试专用加密.zip");
        writeData(pukyfile, pukyData);
        // 加密完成,你可以去尝试找到文件打开试试,会显示文件损坏的

        // 4、解密操作
        // 加载私钥对象
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) loadPrivateKey(prky);
        // 读文件,拿到加密后的文件
        File file2 = new File("D:\\RSA\\RSA测试专用加密.zip");
        // 转byte数组
        byte[] temp = handleReadData(file2);
        // 对加密后的数据进行解密
        byte[] prkyData = decryptByPrivateKey(temp, rsaPrivateKey.getEncoded());
        // 写入到新文件
        File file = new File("D:\\RSA\\RSA测试专用解密.zip");
        writeData(file, prkyData);
        // 解密完成



    }

    public static void createKey(){
        KeyPair keyPair = generateKeyPair();
        saveKeyPair(keyPair);
    }

    /**
     * 生成密钥对
     * @return 密钥对
     */
    public static KeyPair generateKeyPair() {
        try {
            KeyPairGenerator kpg;
            // 添加提供者 BC
            // <!-- 加密工具 -->
            // <dependency>
            //    <groupId>org.bouncycastle</groupId>
            //    <artifactId>bcprov-jdk15on</artifactId>
            //    <version>1.69</version>
            // </dependency>
            Security.addProvider(new BouncyCastleProvider());
            // 密钥对实例化,指定算法及提供者
            kpg = KeyPairGenerator.getInstance(RSA, BC);
            assert kpg!=null : "key generate error.";
            // 密钥对初始化,指定密钥大小
            kpg.initialize(thisSize.getKeySize());
            // 获取生成的密钥对
            return kpg.generateKeyPair();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 保存密钥对
     * @param keyPair 密钥对
     */
    private static void saveKeyPair(KeyPair keyPair) {
        // 如果密钥对存在,则终止重写
        // - 如果使用其他密钥对,导致密钥不识别,需要更换正确的密钥对或密钥等级
        // - 因此,建议使用固定等级的密钥对
        // - 即,只换密钥对,不变等级
        if(areKeysPresent()) return;
        // 写入密钥对文件
        writeDataBuffer(new File(PUBLIC_KEY_FILE), loadPublicKey(keyPair.getPublic()));
        writeDataBuffer(new File(PRIVATE_KEY_FILE), loadPrivateKey(keyPair.getPrivate()));
    }

    /**
     * 判定 密钥文件 是否存在
     * 暂定逻辑为,必须公钥密钥同时存在
     * @return
     */
    private static boolean areKeysPresent() {
        File privateKey = new File(PRIVATE_KEY_FILE);
        File publicKey = new File(PUBLIC_KEY_FILE);
        return privateKey.exists() && publicKey.exists();
    }

    /**
     * 给文件中写入数据
     * @param file 文件对象
     * @param content 字符串对象
     */
    private static void writeDataBuffer(
            File file,
            String content
    ) {
        try {
            if (file.getParentFile() != null) {
                // 建立多级文件夹
                file.getParentFile().mkdirs();
            }
            // 创建新的空文件
            file.createNewFile();

            FileOutputStream stream =  new FileOutputStream(file);
            // 以 UTF-8 编码方式进行写入
            OutputStreamWriter outputStreamWriter =
                    new OutputStreamWriter(stream, UTF8);
            BufferedWriter writer = new BufferedWriter(outputStreamWriter);
            writer.write(content);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 加载公钥字符串
     * @param publicKey 公钥对象
     * @return 公钥字符串
     */
    private static String loadPublicKey(PublicKey publicKey) {
        return keyToString(publicKey);
    }

    /**
     * 加载公钥对象
     * @param key 公钥字符串
     * @return 公钥对象
     */
    private static PublicKey loadPublicKey(String key) {
        try {
            // 如果读取字符串为空,则直接抛出
            if (key == null) {
                throw new RuntimeException("public-key is null.");
            }
            // 通过 公钥字节数组,指定 算法,再次生成 公钥对象
            // 公钥 使用 X509EncodedKeySpec
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
                    java.util.Base64.getDecoder().decode((key.getBytes()))
            );
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            return keyFactory.generatePublic(keySpec);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 加载私钥字符串
     * @param privateKey 私钥对象
     * @return 私钥字符串
     */
    private static String loadPrivateKey(PrivateKey privateKey) {
        return keyToString(privateKey);
    }

    /**
     * 加载私钥
     * @param key 私钥字符串
     * @return 私钥对象
     */
    private static PrivateKey loadPrivateKey(String key) {
        try {
            // 如果读取字符串为空,则直接抛出
            assert key!=null : "private-key is null.";
            // 通过 私钥字节数组,指定 算法,再次生成 私钥对象
            // 私钥 使用 PKCS8EncodedKeySpec
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(
                    java.util.Base64.getDecoder().decode((key.getBytes()))
            );
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            return keyFactory.generatePrivate(keySpec);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将 Key 对象转换成 字符串
     * @param key Key
     * @return 字符串
     */
    private static String keyToString(Key key) {
        try {
            byte[] keyBytes = key.getEncoded();
            return new String(java.util.Base64.getEncoder().encode(keyBytes), UTF8);
        } catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 读取密钥对文件,并赋值给相关对象的属性
     */
    private static void readKeyPair() {
        prky = readDataOnce(PRIVATE_KEY_FILE);
        puky = readDataOnce(PUBLIC_KEY_FILE);
    }

    /**
     * 以 UTF-8 读码方式,一次性读取全部数据
     * - 适用于小型文件
     * - 此处使用在读取完整的密钥
     * @param filePath 文件路径
     * @return 文件内容
     */
    private static String readDataOnce(String filePath) {
        try {
            byte[] bytes = Files.readAllBytes(Paths.get(filePath));
            System.out.println(new String(bytes, StandardCharsets.UTF_8));
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 读取数据(核心)
     * @param file 预读取文件
     * @return 文件相关内容的字节
     * @throws IOException 文件访问异常、权限异常
     */
    private static byte[] handleReadData(File file){

        try {
            // 以 1M 为单位,进行分段读取文件,并重组数据,返回数据相关字节数组
            FileInputStream in = new FileInputStream(file);
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            byte[] tmpBuffer = new byte[READER_1M];
            int count;
            while ((count = in.read(tmpBuffer)) != -1) {
                byteOut.write(tmpBuffer, 0, count);
                tmpBuffer = new byte[READER_1M];
            }
            in.close();
            return byteOut.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过 公钥 进行加密操作
     *
     * @param fileByte 文件字节数组
     * @param publicKeyByte 公钥字节数组
     * @return 加密文件字节数组
     * @throws Exception 异常
     */
    private static byte[] encryptByPublicKey(byte[] fileByte, byte[] publicKeyByte) {

        try {

            // 指定加密算法
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);

            // 生成公钥
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyByte);
            Key publicKey = keyFactory.generatePublic(x509KeySpec);

            // 指定配置并初始化
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            // 进行加密処理
            return handleData(cipher, fileByte, Cipher.ENCRYPT_MODE);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过 私钥 进行加密操作
     *
     * @param dataStr 加密文件字节数组
     * @param privateKeyByte 私钥字节数组
     * @return 文件字节数组
     * @throws Exception 异常
     */
    private static byte[] decryptByPrivateKey(byte[] dataStr, byte[] privateKeyByte) {

        try {
            // 指定加密算法
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);

            // 生成私钥
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKeyByte);
            Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

            // 指定配置并初始化
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);

            // 进行解密処理
            return handleData(cipher, dataStr, Cipher.DECRYPT_MODE);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 処理数据(核心)
     * @param cipher cipher配置对象
     * @param fileByte 文件字节数组
     * @param modeIndex 处理模式
     *                  选项一、Cipher.ENCRYPT_MODE
     *                  选项二、Cipher.DECRYPT_MODE
     * @return
     */
    private static byte[] handleData(Cipher cipher, byte[] fileByte, int modeIndex) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            // 进行模式选择
            // - 根据密钥大小等级,进行模式选择的最值
            int singleMax = modeIndex == Cipher.DECRYPT_MODE
                    ? thisSize.getDecryptSize() : thisSize.getEncryptSize();

            // 获取数据最大长度,并作其余初始化
            int inputLen = fileByte.length;

            int offSet = 0;
            byte[] cache;
            int i = 0;

            // 分段処理进行 加密/解密 操作 (整个文件全部,如果你要加密的文件不大的话,可以使用这个,我这个业务是要加密一个500M的压缩包,所以选择了下面那个代码)
//            while (inputLen - offSet > 0) {
//                if (inputLen - offSet > singleMax) {
//                    cache = cipher.doFinal(fileByte, offSet, singleMax);
//                } else {
//                    cache = cipher.doFinal(fileByte, offSet, inputLen - offSet);
//                }
//                out.write(cache, 0, cache.length);
//                i++;
//                offSet = i * singleMax;
//            }

            // 部分処理进行 加密/解密 操作
            Boolean flag = true;
            while (inputLen - offSet > 0) {
                if (flag){
                    if (inputLen - offSet > singleMax) {
                        cache = cipher.doFinal(fileByte, offSet, singleMax);
                    } else {
                        cache = cipher.doFinal(fileByte, offSet, inputLen - offSet);
                    }
                    out.write(cache, 0, cache.length);
                    flag = false;
                }else {
                    if (inputLen - offSet > singleMax){
                        byte[] bytes = new byte[singleMax];
                        int i1 = offSet;
                        int i2 = singleMax ;
                        System.arraycopy(fileByte,(i1),bytes,0,(i2));
                        cache = bytes;
                        out.write(cache, 0, bytes.length);
                    }else {
                        int i1 = (inputLen - offSet + 1);
                        byte[] bytes = new byte[i1];
                        int i2 =  offSet;
                        int i3 = i1 - 1 ;
                        System.arraycopy(fileByte,(i2),bytes,0,(i3));
                        cache = bytes;
                        out.write(cache, 0, bytes.length);
                    }
                }
                i++;
                offSet = i * singleMax;
            }

            // 公共部分了
            // 数据转换、关闭资源、并返回已处理数据
            byte[] data = out.toByteArray();
            out.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给文件中写入数据
     * @param file 文件对象
     * @param data 数据字节数组
     */
    private static void writeData(File file, byte[] data) {
        try {
            FileOutputStream out = new FileOutputStream(file);
            assert data != null : "write data is null.";
            out.write(data);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

三、执行结果

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值