Security
PDF encryption in UniPDF is the standard security handler and nothing else. A document
gets two passwords and a permission bitmask, all three living in the encryption
dictionary that PdfWriter.Encrypt writes and PdfReader.Decrypt authenticates
against. The constants are in github.com/unidoc/unipdf/v5/core/security; the calls
that use them are on the reader and writer in model.
The two passwords are not interchangeable. The user password opens the document under the restrictions in the bitmask. The owner password grants everything, ignoring the bitmask, and is what a viewer asks for before letting you change the security settings. A file with an empty user password opens for everyone and relies on the bitmask alone.
What the permission bits are worth
They are a declaration, not a mechanism. The bitmask tells a cooperating viewer that printing is not allowed; it does not stop any program from printing. Once a password authenticates - and the user password is enough, or no password at all when the user password is empty - the full content is available and UniPDF will re-save it unencrypted. Restricting permissions is useful for signaling intent to well-behaved software. It is not a way to keep a document out of someone’s hands.
Reading versus writing
Encryption is set on the writer and only takes effect at write time, so Encrypt has
to be called before Write or WriteToFile. Decryption is on the reader and has to
happen before anything else, because the page tree is not loaded until authentication
succeeds.
Which constructor you use matters. model.NewPdfReader does not attempt decryption: it
returns a working reader for an encrypted file with no password, which is what makes
inspection and password-testing possible. NewPdfReaderFromFile and
NewPdfReaderWithOpts decrypt with ReaderOpts.Password immediately and return an
error if that password is wrong.
Algorithms
Three, all standard-handler: RC4-128, AES-128 and AES-256, selected through
EncryptOptions.Algorithm. The zero value is RC4_128bit, so an options struct that
sets only Permissions silently gets the weakest of the three. Pick
model.AES_256bit unless you are targeting a viewer that cannot handle it.
Where to look
| Guide | Covers |
|---|---|
| Get Security Info | Detecting encryption and reporting the algorithm in use. |
| Check PDF Permissions | The permission flags, and testing them with Allowed. |
| Protect PDF | Encrypting output, choosing an algorithm, setting the bitmask. |
| Unlock Password-Protected PDF | Decrypting and writing an unprotected copy. |
Digital signatures are a separate mechanism with their own guides; see signature. Encryption hides content, signatures prove it has not changed, and the two are configured independently.