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

导航

  • FileEncryUtils
    • 测试环境
      • pom依赖
      • log4j.properties
    • 代码

FileEncryUtils

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

测试环境

JDK1.8+idea+maven

pom依赖

	<dependencies>
 
        <dependency>
            <groupId>com.itextpdfgroupId>
            <artifactId>itext7-coreartifactId>
            <version>7.1.4version>
            <type>pomtype>
        dependency>
        <dependency>
            <groupId>org.freemarkergroupId>
            <artifactId>freemarkerartifactId>
            <version>2.3.28version>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poiartifactId>
            <version>3.17version>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poi-ooxmlartifactId>
            <version>3.17version>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>ooxml-schemasartifactId>
            <version>1.1version>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poi-scratchpadartifactId>
            <version>3.17version>
        dependency>
        <dependency>
            <groupId>fr.opensagres.xdocreportgroupId>
            <artifactId>fr.opensagres.xdocreport.converter.docx.xwpfartifactId>
            <version>1.0.6version>
        dependency>

        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.10version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>1.7.21version>
        dependency>

        
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>1.7.25version>
            <scope>compilescope>
        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会报错

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

参考代码

代码原作者

你可能感兴趣的:(博客)