Apache POI decrypt doc file cannot process encrypt

2019-08-07 15:45发布

问题:

public static void decryptedDoc(String path,String[] password) throws FileNotFoundException, IOException{
  FileOutputStream fileOut = null;
  for(int i=0;i<password.length;i++){
//  try{
  Biff8EncryptionKey.setCurrentUserPassword(password[i]);
  NPOIFSFileSystem fs = new NPOIFSFileSystem( new FileInputStream(path));
  HWPFDocument doc=new HWPFDocument(fs.getRoot());
  Biff8EncryptionKey.setCurrentUserPassword(null);
  String neweachpath=path.substring(0, path.length()-4)+"_decrypted"+path.substring(path.length() -4);
  fileOut = new FileOutputStream(neweachpath);
  doc.write(fileOut);
  fileOut.flush(); 
  //}
 /* catch (EncryptedDocumentException e){
      System.out.println("wrong password for"+path+password[i]);
  }*/
  }

I want to use this code to decrypt doc files.

I referenced this code from Apache POI Encryption . It truly works for docx and xls, xlsx files. But it does not work here, always has the following exception even when the password is right.

org.apache.poi.EncryptedDocumentException: Cannot process encrypted word file

It seems the key has not been set correctly.

回答1:

As covered in the diagram in the Apache POI Encryption page that you linked to in your question:

HWPF, the Apache POI component which handles Word .doc files, does not support decrypting password protected .doc files. As such, you will get an Exception if you try (as you have)

As the table explains, all of the OOXML-based formats are supported in their encrypted / password protected form, as those all use a common way of storing the protected content. The older file formats each have their own way of doing things, which requires independent implementations for each format. There's support for the most common kind used for xls in HSSF, for one of the kinds used in ppt in HSLF, but no doc support in HWPF.

If this really matters to you, you'll need to read through the Microsoft published file format documentation to work out how .doc files do encryption, then add in the support and contribute it back. Links for that are available in the Apache POI - Contribution Guidelines page