java实现文件加密(word、excel、pdf、ppt)

FileEncryUtils

提供word、excel、pdf、ppt的加密

测试环境

JDK1.8+idea+maven

pom依赖

	<dependencies>
 
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext7-core</artifactId>
            <version>7.1.4</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>ooxml-schemas</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>fr.opensagres.xdocreport.converter.docx.xwpf</artifactId>
            <version>1.0.6</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.21</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
            <scope>compile</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>-->
    </dependencies>

log4j.properties

#定义输出级别
log4j.rootLogger=DEBUG,Console
#日志输出方式:控制台输出

log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.Encoding=UTF-8

#可以灵活地指定布局模式
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
#log4j.appender.Console.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss.SSS} -%p (%F\:%L)- %m%n
#打印格式例子:2017-08-11 15:36 -DEBUG (HttpServletBean.java:174)- Servlet 'mvc' configured successfully
log4j.appender.Console.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm} -%p (%F\:%L)- %m%n

代码

package util;

import java.io.*;

import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import com.itextpdf.kernel.pdf.EncryptionConstants;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.ReaderProperties;
import com.itextpdf.kernel.pdf.WriterProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author :Lizhipeng
 * @date :Created in 2020/5/27 14:29
 * @description:
 * @modified By:
 * @version:
 */
public class FileEncryUtils {
    private static Logger LOGGER = LoggerFactory.getLogger(FileEncryUtils.class);

    /**
     * 加密WORD文档(doc)
     * @param sourceFilePath	源文件
     * @param targetFilePath	目标文件
     * @param password 		 	密码
     * @return
     * @throws Exception
     */
    public static boolean encrypDOC(String sourceFilePath, String targetFilePath, String password) throws Exception{
        return encrypDOC(sourceFilePath, new FileOutputStream(targetFilePath), password);
    }


    public static boolean encrypDOC(String sourceFilePath, OutputStream out, String password) throws IOException {
        POIFSFileSystem fs = null;
        HWPFDocument doc = null;
        try {
            fs = new POIFSFileSystem(new FileInputStream(sourceFilePath));
            doc = new HWPFDocument(fs);
            Biff8EncryptionKey.setCurrentUserPassword(password);
            doc.write(out);
            return true;
        } catch (Exception e) {
            LOGGER.error("DOC文档加密失败:{}",e.getMessage());
            return false;
        }finally {
//            FileUtils.close(doc);
            doc.close();
//            FileUtils.close(fs);
            fs.close();
//            FileUtils.close(out);
            out.close();
        }

    }

    /**
     * 加密EXCEL文档(xls)
     * @param sourceFilePath	源文件
     * @param targetFilePath	目标文件
     * @param password 		 	密码
     * @return
     * @throws Exception
     */
    public static boolean encrypXLS(String sourceFilePath, String targetFilePath, String password) throws Exception{
        return encrypXLS(sourceFilePath, new FileOutputStream(targetFilePath), password);
    }

    public static boolean encrypXLS(String sourceFilePath, OutputStream out, String password) throws IOException {
        POIFSFileSystem fs = null;
        HSSFWorkbook hwb = null;
        try {
            fs = new POIFSFileSystem(new FileInputStream(sourceFilePath));
            hwb = new HSSFWorkbook(fs);
            Biff8EncryptionKey.setCurrentUserPassword(password);
            hwb.write(out);
            return true;
        } catch (Exception e) {
            LOGGER.error("XLS文档加密失败:{}",e.getMessage());
            return false;
        }finally {
//            FileUtils.close(hwb);
//            FileUtils.close(fs);
//            FileUtils.close(out);
            hwb.close();
            fs.close();
            out.close();
        }

    }

    /**
     * 加密PPT文档(ppt)
     * @param sourceFilePath	源文件
     * @param targetFilePath	目标文件
     * @param password 		 	密码
     * @return
     * @throws Exception
     */
    public static boolean encrypPPT(String sourceFilePath, String targetFilePath, String password) throws Exception{
        return encrypPPT(sourceFilePath, new FileOutputStream(targetFilePath), password);
    }

    public static boolean encrypPPT(String sourceFilePath, OutputStream out, String password) throws IOException {
        POIFSFileSystem fs = null;
        HSLFSlideShow hss = null;
        try {
            fs = new POIFSFileSystem(new FileInputStream(sourceFilePath));
            hss = new HSLFSlideShow(fs);
            Biff8EncryptionKey.setCurrentUserPassword(password);
            hss.write(out);
            return true;
        } catch (Exception e) {
            LOGGER.error("PPT文档加密失败:{}",e.getMessage());
            return false;
        }finally {
//            FileUtils.close(hss);
//            FileUtils.close(fs);
//            FileUtils.close(out);
            hss.close();
            fs.close();
            out.close();
        }

    }

    /**
     * 加密PDF文档
     * @param sourceFilePath	源文件
     * @param targetFilePath	目标文件
     * @param password 		 	密码
     * @return
     * @throws Exception
     */
    public static boolean encrypPDF(String sourceFilePath, String targetFilePath, String password) throws Exception{
        return encrypPDF(sourceFilePath, new FileOutputStream(targetFilePath), password);
    }

    public static boolean encrypPDF(String sourceFilePath, OutputStream out, String password) throws IOException {
        PdfDocument pdfDoc = null;
        PdfReader reader = null;
        try {
            reader = new PdfReader(sourceFilePath, new ReaderProperties().setPassword("World".getBytes()));
            PdfWriter writer = new PdfWriter(out,
                    new WriterProperties().setStandardEncryption(password.getBytes(), password.getBytes(),
                            EncryptionConstants.EMBEDDED_FILES_ONLY,
                            EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA));
            pdfDoc = new PdfDocument(reader, writer);
            return true;
        } catch (Exception e) {
            LOGGER.error("PDF文档加密失败:{}",e.getMessage());
            return false;
        }finally {
//            FileUtils.close(pdfDoc);
//            FileUtils.close(reader);
            pdfDoc.close();
            reader.close();


        }

    }



    /**
     * 加密xml文档(docx,xlsx,pptx)
     * @param sourceFilePath	源文件
     * @param targetFilePath	目标文件
     * @param password 		 	密码
     * @return
     * @throws Exception
     */
    public static boolean encrypXML(String sourceFilePath, String targetFilePath, String password)  throws Exception{
        return encrypXML(sourceFilePath, new FileOutputStream(targetFilePath), password);
    }

    public static boolean encrypXML(String sourceFilePath, OutputStream out, String password) throws IOException {
        POIFSFileSystem fs = null;
        try {
            fs = new POIFSFileSystem();
            EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
            Encryptor enc = info.getEncryptor();
            enc.confirmPassword(password);
            try (OPCPackage opc = OPCPackage.open(new File(sourceFilePath), PackageAccess.READ_WRITE);
                 OutputStream os = enc.getDataStream(fs)) {
                opc.save(os);
            }
            fs.writeFilesystem(out);
            return true;
        } catch (Exception e) {
            LOGGER.error("XML文档加密失败:{}",e.getMessage());
            return false;
        } finally {
//            FileUtils.close(fs);
//            FileUtils.close(out);
            fs.close();
            out.close();
        }


    }

    /**
     * 加密文档
     * @param sourceFilePath	源文件
     * @param targetFilePath	目标文件
     * @param password 		 	密码
     * @return
     */
    public static boolean encryFile(String sourceFilePath, String targetFilePath, String password){
        try {
            return encryFile(sourceFilePath, new FileOutputStream(targetFilePath), password);
        } catch (Exception e) {
            LOGGER.error("文档加密失败:{}",e.getMessage());
        }
        return false;

    }

    public static boolean encryFile(String sourceFilePath, OutputStream out, String password){
        boolean flag = false;
        try {
            int index = sourceFilePath.indexOf(".");
            if(index > 0) {
                String suffix = sourceFilePath.substring(index+1);
                if("doc".equalsIgnoreCase(suffix)) {
                    flag = encrypDOC(sourceFilePath, out, password);
                }else if("xls".equalsIgnoreCase(suffix)) {
                    flag = encrypXLS(sourceFilePath, out, password);
                }else if("ppt".equalsIgnoreCase(suffix)) {
                    flag = encrypPPT(sourceFilePath, out, password);
                }else if("pdf".equalsIgnoreCase(suffix)) {
                    flag = encrypPDF(sourceFilePath, out, password);
                }else if("docx".equalsIgnoreCase(suffix) || "xlsx".equalsIgnoreCase(suffix) || "pptx".equalsIgnoreCase(suffix)){
                    flag = encrypXML(sourceFilePath, out, password);
                }else {
                    LOGGER.warn("无法识别的文件类型");
                }
            }
        } catch (Exception e) {
            LOGGER.error("文档加密失败:{}",e.getMessage());
        }
        return flag;
    }

    /**
     * 简单测试
     * @param args
     */
    /*public static void main(String[] args) {
        boolean flag = FileEncryUtils.encryFile("C:/Users/Lzp's_computer/Desktop/测试文件.docx", "加密.docx", "password");
        LOGGER.info(String.valueOf(flag));
    }*/
}

遇到的错误:

SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

解决办法:导入slf4j12这个依赖(slf4j-nop也行),只用slf4j-api会报错

有更简单粗暴的文件加密方法或思路请不吝赐教

参考代码

代码原作者

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鹏晓星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值