Password Encryption
When Word, Excel or PowerPoint saves a file with Encrypt with Password, the
result is no longer a ZIP package. The package is encrypted with AES and stored
inside an OLE compound file next to an EncryptionInfo stream that describes
how the key was derived. Nothing in the file is readable without the password.
UniOffice reads and writes that format from v2.15.0, in all three packages, with
the same two option types from github.com/unidoc/unioffice/v2/crypto.
| Package | Open | Save |
|---|---|---|
document | document.OpenWithOptions, document.ReadWithOptions | Document.SaveToFileWithOptions, Document.SaveWithOptions |
spreadsheet | spreadsheet.OpenWithOptions, spreadsheet.ReadWithOptions | Workbook.SaveToFileWithOptions, Workbook.SaveWithOptions |
presentation | presentation.OpenWithOptions, presentation.ReadWithOptions | Presentation.SaveToFileWithOptions, Presentation.SaveWithOptions |
This is a different feature from the passwords on Restrict Editing and sheet protection. Those store a hash of a password and ask Office to refuse edits, but the content stays in plain XML that anyone can unzip. Encryption is the one to use when the content itself has to stay private.
Save an encrypted file
Pass a crypto.SaveOptions with a password to the *WithOptions save call.
Everything else about building the document is unchanged.
doc := document.New()
defer doc.Close()
doc.AddParagraph().AddRun().AddText("This document is encrypted with a password.")
opts := &crypto.SaveOptions{
Password: "unioffice",
Encryption: crypto.EncryptionAES256,
}
if err := doc.SaveToFileWithOptions("encrypted.docx", opts); err != nil {
return err
}A workbook and a presentation take the same options through
wb.SaveToFileWithOptions and ppt.SaveToFileWithOptions.
UniOffice always writes agile encryption, the scheme Office has written since
Office 2010. Encryption only picks the key size:
Encryption | Cipher | Hash |
|---|---|---|
crypto.EncryptionDefault (the zero value) | AES-256 | SHA-512 |
crypto.EncryptionAES256 | AES-256 | SHA-512 |
crypto.EncryptionAES192 | AES-192 | SHA-512 |
crypto.EncryptionAES128 | AES-128 | SHA-512 |
The key is derived from the password with 100000 rounds of SHA-512 and a random salt per file, so the same password gives different bytes each time it is saved.
An empty Password is not an error. A nil *SaveOptions or a SaveOptions
with Password: "" writes an ordinary, unencrypted package, exactly like
SaveToFile. If the password comes from configuration or user input, check
that it is not empty before saving, or a missing setting quietly produces a
plaintext file.
Open an encrypted file
Pass the password in a crypto.OpenOptions:
doc, err := document.OpenWithOptions("encrypted.docx", &crypto.OpenOptions{Password: "unioffice"})
if err != nil {
return err
}
defer doc.Close()Reading supports both AES schemes Office produces: agile, and the older standard
encryption Office 2007 wrote. Once opened, the document is an ordinary
*document.Document and every other guide applies to it.
The password is only used when the file is actually encrypted. Given an ordinary
.docx, OpenWithOptions ignores the password and opens it normally. So when
your program has a password for a file that may or may not be encrypted, call
OpenWithOptions every time rather than checking first.
The other order works too. The plain Open and Read recognize an encrypted
file and return unioffice.ErrEncryptedDocument, which is the signal to ask the
user for a password and retry with OpenWithOptions.
Errors
The errors are sentinel values in the root package,
github.com/unidoc/unioffice/v2. Compare them with errors.Is.
| Situation | Error |
|---|---|
Encrypted file opened with plain Open/Read, or with an empty password | unioffice.ErrEncryptedDocument |
| Wrong password | unioffice.ErrIncorrectPassword |
| An encryption scheme UniOffice does not read | unioffice.ErrUnsupportedEncryption |
Pre-2007 binary .doc, .xls or .ppt | unioffice.ErrLegacyBinaryFormat |
doc, err := document.OpenWithOptions(path, &crypto.OpenOptions{Password: password})
switch {
case errors.Is(err, unioffice.ErrIncorrectPassword):
return errAskAgain
case errors.Is(err, unioffice.ErrUnsupportedEncryption):
return errResaveInOffice
case err != nil:
return err
}
defer doc.Close()Remove or change the password
An opened document does not remember that it was encrypted. SaveToFile writes
it back as a plain package, which is how you decrypt a file:
doc, err := document.OpenWithOptions("encrypted.docx", &crypto.OpenOptions{Password: "unioffice"})
if err != nil {
return err
}
defer doc.Close()
if err := doc.SaveToFile("decrypted.docx"); err != nil {
return err
}The flip side matters more. If you open an encrypted file to edit it and save
with SaveToFile, the result is unencrypted. To keep it encrypted, save with
SaveToFileWithOptions again. Passing a different password there is how you
change it.
Streams and memory
ReadWithOptions(r io.ReaderAt, size int64, opts) and
SaveWithOptions(w io.Writer, opts) do the same work as the file variants
without touching disk, which is what you want when the file comes from object
storage or goes straight out in an HTTP response.
var buf bytes.Buffer
if err := wb.SaveWithOptions(&buf, &crypto.SaveOptions{Password: password}); err != nil {
return err
}
wb2, err := spreadsheet.ReadWithOptions(bytes.NewReader(buf.Bytes()), int64(buf.Len()), &crypto.OpenOptions{Password: password})Encryption is not streamed. Saving builds the complete ZIP package in a buffer and then encrypts it into a second one, and opening decrypts the whole package into a byte slice before parsing it. For large files, budget memory for the package twice over, on top of the parsed document.
Limitations
UniOffice writes agile encryption only. It never writes standard encryption, so a file it produces needs Office 2010 or later, or another reader that supports agile encryption.
RC4 and CryptoAPI encryption are not supported on read. They come from Office
97-2003 and from some older third-party tools that apply them to .docx and
.xlsx files. Opening one fails whatever the password, but not always with
ErrUnsupportedEncryption: a CryptoAPI header can get as far as key derivation
and fail with a plain decryption error. Saving the file again with a password
from a current Office version switches it to AES.
The password is the only secret. UniOffice stores no key of its own and has no
recovery path, so a lost password means the content is gone. Encryption also
does nothing for a document once it is open in your process: the decrypted
Document lives in memory like any other.
Encryption and protection are independent and can be combined. A workbook can have sheet protection and be saved encrypted, and anyone with the encryption password then sees a protected sheet.
Run the examples
Four examples cover this guide, one per package plus one for the error cases.
| Example | Shows |
|---|---|
document/encrypt-document | Saving with each key size and opening the result. |
document/decrypt-document | The errors from plain Open and from a wrong password, then saving a decrypted copy. |
spreadsheet/encrypt-spreadsheet | Saving and reopening an encrypted workbook. |
presentation/encrypt-presentation | Saving and reopening an encrypted presentation. |
git clone https://github.com/unidoc/unioffice-examples.git
cd unioffice-examples/document/decrypt-document
go run main.goIf this is your first time using UniOffice, follow the getting started guide to create an API key and set up your development environment.
The program writes encrypted.docx, prints the error from each failed open,
prints the document text, and writes decrypted.docx without a password.