Encrypt and Decrypt Word Document in Java

This article demonstrates how to encrypt a Word document with a password as well as remove the encryption by using Spire.Doc for Java.

Encrypt 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("C:\\Users\\Administrator\\Desktop\\sample.docx");

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

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

Decrypt 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("C:\\Users\\Administrator\\Desktop\\Encrypt.docx", FileFormat.Docx, "abc-123");

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