簡體   English   中英

如何使用Apache POI解密.doc / docx文件?

[英]How to decrypt a .doc/docx file with Apache POI?

我正在嘗試使用Apache POI打開受密碼保護的.doc文件。 但是,我得到了錯誤。

org.apache.poi.EncryptedDocumentException:無法處理加密的單詞文件

誰能幫我解決這個問題。 如果能得到我的代碼,我將不勝感激。

EncryptedDocumentException表示您正在嘗試處理以前未“解鎖”的加密文檔。

以下代碼段適合檢查基於XML的格式( .xlsx,.pptx,.docx等 )是否適用,以便以后可以安全地對其進行處理:

String password = "secret"; // set password
File fileToProcess; // obtain/read/open the file here....
NPOIFSFileSystem filesystem  = new NPOIFSFileSystem(fileToProcess);
EncryptionInfo info = new EncryptionInfo(filesystem);
Decryptor d = Decryptor.getInstance(info);

try {
    if (!d.verifyPassword(password)) {
        throw new RuntimeException("Unable to process: document is encrypted");
    }

    InputStream dataStream = d.getDataStream(filesystem);

    // parse dataStream as the document is now processable from here on
    // ...

} catch (GeneralSecurityException ex) {
    throw new RuntimeException("Unable to process encrypted document", ex);
}

上面的示例摘自官方POI文檔的加密部分,並根據項目的JavaDoc進行了修改。 您可能要檢查/讀取Decryptor和/或NPOIFSFileSystem類的JavaDoc。

如果要轉換二進制文件格式( .xls,.ppt,.doc等 ),請查看加密部分以獲取代碼示例。

希望能幫助到你。

由於問題最初是關於解密二進制*.doc格式的:

Apache POI加密支持中的代碼二進制格式需要一點點更新才能與HWPF一起使用。 HWPFDocument不能從創建NPOIFSFileSystem 需要POIFSFileSystem 但是其他都是一樣的。

運行此代碼后,使用密碼“ pass”對file.doc加密,新文件fileDecrypted.doc被解密,並且無需密碼即可打開。

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.hwpf.HWPFDocument;

import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class ReadEncryptedHWPF {

 public static void main(String[] args) throws Exception {

  Biff8EncryptionKey.setCurrentUserPassword("pass"); 
  POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("file.doc")); 
  HWPFDocument doc = new HWPFDocument(fs);
  Biff8EncryptionKey.setCurrentUserPassword(null);
  doc.write(new FileOutputStream("fileDecrypted.doc"));
  doc.close();

  doc = new HWPFDocument(new FileInputStream("fileDecrypted.doc"));
  org.apache.poi.hwpf.extractor.WordExtractor extractor = new org.apache.poi.hwpf.extractor.WordExtractor(doc);
  System.out.println(extractor.getText());
  extractor.close();

 }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM