使用AES加密文件 并且使用RSA加密AES公钥嵌入加密文件中 实现双重加密

此篇博客介绍了如何使用AES加密配合RSA算法,实现文件的安全加密。详细步骤包括生成AES密钥,用RSA公钥加密AES密钥,并将其写入目标文件头,确保源文件的安全保护。

AES加密文件:

 /**
     * 加密文件
     * @param sourceFile 源文件(未加密文件)
     * @param tragetFile 目标文件名(加密后文件)
     * @publicKeys RSA公钥
     */
    public static boolean encodeFile(File sourceFile, String  tragetFile, String publicKeys) {
        OutputStream out = null;
        InputStream in = null;
        try {
            if (!sourceFile.exists()) {
                return false;
            }
            KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
            keyGen.init(KEY_SIZE);
            /**
             * 随机生成AES密钥
             */
            SecretKey key = keyGen.generateKey();
            Key publicKey = RSAUtils.getPublicKey(publicKeys);
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.WRAP_MODE, publicKey);
            /**
             * 使用RSA公钥加密AES密钥
             */
            byte[] wrappedKey = cipher.wrap(key);
            out = new FileOutputStream(tragetFile);

            /**
             *  将加密后的AES密钥写入加密文件头部
             */
            out.write(wrappedKey, 0, wrappedKey.length);
            in = new FileInputStream(sourceFile);

            /**
             * AES加密文件
             */
            copyStream(key, in, out, true);
            return true;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return false;
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return false;
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            return false;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
            return false;
        } catch (BadPaddingException e) {
            e.printStackTrace();
            return false;
        } finally {
            return freeSource(out, in);
        }
    }
    ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值