通过base64实现单个文件的加密解密


import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Base64;

/**
 * base64实现单个文件的加密解密
 *
 * @author syl
 */
@Slf4j
public class PictureEncryption {
    private static InputStream in=null;
    private static OutputStream out=null;


    /**
     *
     * @param encode 要解密的
     * @param decodePath 解密路径
     * @throws IOException
     */
    private static void decodeFile(byte[] encode,String decodePath) throws IOException {
        //图片的解密
        log.info("开始解密.....");
        byte[] decode = Base64.getDecoder().decode(encode);
        File deFile = new File(decodePath);
        if (!deFile.exists()){
            deFile.createNewFile();
        }
        out=new BufferedOutputStream(new FileOutputStream(deFile));
        out.write(decode);
        log.info("解密完成.....");
    }

    /**
     *
     * @param srcPath 要加密的文件
     * @param encodePath 加密之后的文件 xxx.txt
     * @return
     * @throws IOException
     */
    private static byte[] fileEncode(String srcPath,String encodePath) throws IOException {
        log.info("开始加密.....");
        File file=new File(srcPath);
        in=new BufferedInputStream(new FileInputStream(file));
        int available = in.available();
        byte [] bytes=new byte[available];
        in.read(bytes);
        in.close();
        byte[] encode = Base64.getEncoder().encode(bytes);
        File enFile = new File(encodePath);
        if (!enFile.exists()){
            enFile.createNewFile();
        }
        out=new BufferedOutputStream(new FileOutputStream(enFile));
        out.write(encode);
        log.info("加密完成.....");
        return encode;
    }

    public static void main(String[] args) {
        try {
            //图片的加密
            String srcPath = "H:\\pic\\地址.xlsx";
            String encodePath = "H:\\pic\\加密2.txt";
            byte[] encode = fileEncode(srcPath,encodePath);
            String decodePath="H:\\pic\\地址1.xlsx";
            decodeFile(encode,decodePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值