Protection and Encryption
Overview
This guide shows how to protect a Word document against editing with a password, encrypt a DOCX file so that it needs a password to open, and open it again in Java with Aspose.Words FOSS for Java. A protected Word document records which kind of editing is allowed, and an encrypted file needs a password to open. Document.protect marks the document as protected with one of the ProtectionType values and an optional password, Document.unprotect removes the protection, and Document.getProtectionType returns the current value. Encryption is separate: OoxmlSaveOptions.setPassword makes Document.save write an encrypted DOCX file, and LoadOptions with the password opens it again. A wrong or missing password raises an IncorrectPasswordException. This page protects a document and removes the protection, lists the protection types, and encrypts and reopens a file. The three examples were compiled and run against the published package on Java 8, 17 and 21 with identical output.
Prerequisites
| Requirement | Detail |
|---|---|
| Java | 8 or later |
| Dependency | The package from Installation |
| Import | import com.aspose.words.*; |
| Code | The examples are statements. Put them in a method that declares throws Exception. |
Protect a Document and Remove the Protection
protect(ProtectionType.READ_ONLY, password) protects the document, and the setting is saved with the file: the reloaded document reported READ_ONLY. unprotect(password) returns a boolean. In the example a wrong password returned false and left the document READ_ONLY, and the right password returned true and the type became NO_PROTECTION. In a probe that unzipped the saved file on Java 8, 17 and 21, word/settings.xml contained a w:documentProtection element with w:edit="readOnly" and w:enforcement="1" and a w:hash and a w:salt attribute; the password text itself did not appear in word/settings.xml. The same probe showed that protection does not stop your own code: DocumentBuilder.writeln after protect still added text, and the saved file still read READ_ONLY.
import com.aspose.words.*;
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Quarterly figures");
System.out.println("Before protect: " + ProtectionType.getName(doc.getProtectionType()));
doc.protect(ProtectionType.READ_ONLY, "review-2024");
System.out.println("After protect: " + ProtectionType.getName(doc.getProtectionType()));
doc.save("protected.docx");
Document reloaded = new Document("protected.docx");
System.out.println("Reloaded: " + ProtectionType.getName(reloaded.getProtectionType()));
System.out.println("Wrong password removes protection: " + reloaded.unprotect("guess"));
System.out.println("Still: " + ProtectionType.getName(reloaded.getProtectionType()));
System.out.println("Right password removes protection: " + reloaded.unprotect("review-2024"));
System.out.println("Now: " + ProtectionType.getName(reloaded.getProtectionType()));The program printed:
Before protect: NO_PROTECTION
After protect: READ_ONLY
Reloaded: READ_ONLY
Wrong password removes protection: false
Still: READ_ONLY
Right password removes protection: true
Now: NO_PROTECTIONThe Protection Types and protect With One Argument
ProtectionType has five protection values as int constants (the class also has a public length constant, 5, that is not a protection type): ALLOW_ONLY_REVISIONS (0), ALLOW_ONLY_COMMENTS (1), ALLOW_ONLY_FORM_FIELDS (2), READ_ONLY (3) and NO_PROTECTION (-1). ProtectionType.getName returns the constant name as a string, which the example prints. Each of the four protection types survived a save and a reload. unprotect() without an argument removes the protection of a document that has a password: after it the type was NO_PROTECTION. protect(type) with one argument assigns a password that you cannot supply: the upstream documentation calls it random, and in a probe the saved word/settings.xml contained a w:hash and a w:salt attribute (the same values on every run). That is why unprotect("guess") returned false in the example; call unprotect() to remove this protection. In a probe, protect(type, null) and protect(type, "") saved the element without a hash, and unprotect("guess") and unprotect("") still returned false, so use unprotect() for those as well.
import com.aspose.words.*;
int[] types = {
ProtectionType.ALLOW_ONLY_REVISIONS,
ProtectionType.ALLOW_ONLY_COMMENTS,
ProtectionType.ALLOW_ONLY_FORM_FIELDS,
ProtectionType.READ_ONLY
};
for (int i = 0; i < types.length; i++) {
Document doc = new Document();
new DocumentBuilder(doc).writeln("Contract draft");
doc.protect(types[i], "pw");
String file = "contract_" + i + ".docx";
doc.save(file);
Document reloaded = new Document(file);
System.out.println(ProtectionType.getName(types[i]) + " -> " + ProtectionType.getName(reloaded.getProtectionType()));
}
Document locked = new Document("contract_3.docx");
locked.unprotect();
System.out.println("After unprotect(): " + ProtectionType.getName(locked.getProtectionType()));
Document oneArgument = new Document();
oneArgument.protect(ProtectionType.ALLOW_ONLY_COMMENTS);
oneArgument.save("one_argument.docx");
Document check = new Document("one_argument.docx");
System.out.println("protect with one argument: " + ProtectionType.getName(check.getProtectionType()));
System.out.println("Guess works: " + check.unprotect("guess"));The program printed:
ALLOW_ONLY_REVISIONS -> ALLOW_ONLY_REVISIONS
ALLOW_ONLY_COMMENTS -> ALLOW_ONLY_COMMENTS
ALLOW_ONLY_FORM_FIELDS -> ALLOW_ONLY_FORM_FIELDS
READ_ONLY -> READ_ONLY
After unprotect(): NO_PROTECTION
protect with one argument: ALLOW_ONLY_COMMENTS
Guess works: falseEncrypt a DOCX File With a Password and Open It Again
Set the password on an OoxmlSaveOptions object and pass it to doc.save. FileFormatUtil.detectFileFormat(file).isEncrypted() printed false for a normal DOCX and true for the encrypted one. In a probe on Java 8, 17 and 21 the encrypted file began with the bytes D0CF11E0A1B11AE1 where an ordinary DOCX begins with PK, java.util.zip.ZipFile could not open it, and it did not contain the document text. Opening it without a password, or with a wrong one, threw IncorrectPasswordException with the message The document password is incorrect. in the example; new Document(file, new LoadOptions(password)) opened it and the text was read back. The password is case sensitive and an empty password failed in the same way in the probe.
import com.aspose.words.*;
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Confidential text");
OoxmlSaveOptions saveOptions = new OoxmlSaveOptions();
saveOptions.setPassword("open-sesame");
doc.save("encrypted.docx", saveOptions);
doc.save("plain.docx");
System.out.println("plain.docx encrypted: " + FileFormatUtil.detectFileFormat("plain.docx").isEncrypted());
System.out.println("encrypted.docx encrypted: " + FileFormatUtil.detectFileFormat("encrypted.docx").isEncrypted());
try {
new Document("encrypted.docx");
} catch (IncorrectPasswordException e) {
System.out.println("No password: " + e.getMessage());
}
try {
new Document("encrypted.docx", new LoadOptions("wrong"));
} catch (IncorrectPasswordException e) {
System.out.println("Wrong password: " + e.getMessage());
}
Document opened = new Document("encrypted.docx", new LoadOptions("open-sesame"));
System.out.println("Right password: " + opened.getText().trim());The program printed:
plain.docx encrypted: false
encrypted.docx encrypted: true
No password: The document password is incorrect.
Wrong password: The document password is incorrect.
Right password: Confidential textTips and Best Practices
- Use
unprotect()when you only need to lift the protection in code, andunprotect(password)when you want to check a password: it returns false for a wrong one instead of throwing. - Encryption is applied by the save options only. In a probe, a document opened with its password and saved again with
doc.save(file)was written as an ordinary, unencrypted DOCX (it began with PK), so pass theOoxmlSaveOptionsagain to encrypt the new file. - Protection and encryption can be combined: in a probe, a document protected as READ_ONLY with the password edit and saved with an open password was opened with
LoadOptions, reported READ_ONLY, andunprotect("edit")returned true.
Common Issues
| Issue | Cause | Fix |
|---|---|---|
| The compiler reports cannot find symbol for Document. | The com.aspose.words package is not imported. | Add import com.aspose.words.*;. |
| The compiler reports an unreported exception. | The Document constructors, Document.save and some other methods declare throws Exception. | Declare it on the calling method or catch it. |
IncorrectPasswordException is thrown when opening a file. | The file is encrypted and the password is missing, wrong or differs in case. The exception message was The document password is incorrect. in all three cases. | Pass the password with new LoadOptions(password) and catch IncorrectPasswordException. |
unprotect("guess") returns false although I never set a password. | protect(type) with one argument assigns a password that you cannot supply. With a null or an empty password the tests also gave false for unprotect("guess") and unprotect(""). | Call unprotect() with no argument. |
FAQ
What is the difference between protecting and encrypting a document?
protect sets a protection type that is saved in the document settings, and the file can still be opened without a password. Encryption, set with OoxmlSaveOptions.setPassword, makes the saved file need a password to open: in the example new Document("encrypted.docx") without a password threw IncorrectPasswordException.
How do I know whether a file is encrypted before I open it?
FileFormatUtil.detectFileFormat(file).isEncrypted() returns true for an encrypted file; the example printed true for the encrypted DOCX and false for the plain one.
Can I load an encrypted document from a stream?
Yes. In a probe new Document(inputStream, new LoadOptions(password)) opened the encrypted DOCX and read its text, and doc.save(outputStream, saveOptions) with the password set wrote an encrypted file. Other save formats were not tested.
API Reference Summary
| Class / Method | Description |
|---|---|
ProtectionType | Protection type for a document. |
Document.protect(type, password) | Protects the document from changes and optionally sets a protection password. |
Document.unprotect() | Removes protection from the document regardless of the password. |
Document.unprotect(password) | Removes protection from the document if a correct password is specified. |
Document.getProtectionType() | Gets the currently active document protection type. |
OoxmlSaveOptions | Allows to specify additional options when saving a document into the Docx, Dotx, Docm, Dotm or Flat OPC format; setPassword sets the password used to encrypt the saved file. |
LoadOptions | Allows to specify additional options (such as password or base URI) when loading a document into a Document object. |
IncorrectPasswordException | Thrown if a document is encrypted with a password and the password specified when opening the document is incorrect or missing. |
FileFormatInfo.isEncrypted() | Returns true if the document is encrypted and requires a password to open. |
Related Guides
- Loading Documents
- Saving Documents
- Working with Documents
- Tracked Changes
- Digital Signatures
- How to Protect and Encrypt a Word Document with a Password in Java (knowledge base)