Encrypt/ Decrypt Word Document using Java

In daily work, it’s necessary for us to encrypt some important Word documents to prevent others from snooping on the confidential content. In this article, I will share how to use a 3rd party free Java library to encrypt and decrypt Word documents with simple code.

1. Import the jar dependency of a 3rd party free API to your Java application (2 methods)

● Download the free API (Free Spire.Doc for Java) and unzip it, then add the Spire.Doc.jar file to your Java application as dependency.

● Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

2. Example of encrypt a Word document:

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class EncryptWord {

public static void main(String[] args) {

//create a Document object
Document document = new Document();

//load a Word document
document.loadFromFile("test.docx");

//encrypt the document with a password
document.encrypt("abc-123");

//save as docx file
document.saveToFile("out/Encrypt.docx", FileFormat.Docx);
}
}

3. Example of decrypt a Word document:

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class DecryptWord {

public static void main(String[] args) {

//create a Document object
Document document = new Document();

//remove encryption while loading the password protected document
document.loadFromFile("out/Encrypt.docx", FileFormat.Docx, "abc-123");

//save as docx file.
document.saveToFile("out/Decrypt.docx", FileFormat.Docx);
}
}

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store