I want to add a password to my word file (.doc). I searched for it in google, but found only a solution for (.docx). Can anyone help me? I am using this code, but the output file does not have a password.
FileInputStream in = new FileInputStream("Doccc.doc");
BufferedInputStream bin = new BufferedInputStream(in);
POIFSFileSystem poiFileSystem = new POIFSFileSystem(bin);
Biff8EncryptionKey.setCurrentUserPassword("P@ssw0rd");
HWPFDocument doc = new HWPFDocument(poiFileSystem);
Range range = doc.getRange();
FileOutputStream out = new FileOutputStream("Doccc.doc");
doc.write(out);
out.close();
As Gagravarr pointed out, the page for supported encryption / password protection matrix pretty much sums it up. With the standard library you won't be able to set a password.
You may have an option to implement it, if the details are described in the binary formats specification for the Word file format. Some years ago, I built a custom HWPF library for a client, so I spent a lot of time with analyzing the file format and reading the specs. However, I don't remember the sections about encryption / protection, probably because they were not relevant to me.
If it is possible to add protection with a reasonable amount of work:
.docfiles are stored in the OLE2 compound document format. This format contains the actual Word related data. (If you are new to this, you might think of it as an archiver format - maybe like a ZIP file without compression.) The OLE2 part is well supported (modulePOIFS). The binary Word file format (moduleHWPF) is not so well supported. If you read a Word file into aHWPFDocumentand write that out again, you very likely end up with an invalid document.So if it is possible to add protection without having to read and write out the
HWPFDocument, you have a chance. If modification of the Word data part is needed, and it is only small, maybe changing a couple of bytes (not inserting or removing) without reading and writing theHWPFDocument, then you also have a chance. But if implementing the protection requires changes to a lot of Word file format structures, you likely won't finish this part of the project within months (maybe years, if you are a one-man-team :-) ).