Encrypt PDF Document in C#/VB.NET

Encrypting PDF is a way people commonly used to protect PDF. Whether for a company or for individual, using PDF encryption to place some certain restrictions is indispensable. In order to make the PDF document available to read but unable to modify by unauthorized users, two passwords are required for an encrypted PDF document: owner password and user password. This section will particularly introduce a simple solution to quickly encrypt PDF with C#, VB.NET via Spire.PDF for .NET.

Spire.PDF for .NET as a .NET PDF component, can encrypt your PDF by owner and user password. Owner password is provided to fully access to PDF file such as reset password and restrictions. While user password allows users to open the document as well as subject to the restrictions placed by owner.

In the encryption solution, an object of the PDFSecurity class which is included in the namespace Spire.PDFDocument.Security is used to set the owner and user password. Please feel free to download Spire.PDF for .NET and load your PDF file and then protect it.

Protect PDF by setting password and specify document restrictions.

Step 1: Set PDF key size by the enum."Spire.Pdf.Security.PdfEncryptionKeySize".Three kinds of key size are available here: Key128Bit, Key256Bit and Key40Bit, you can use any one among the three.

[C#]
doc.Security.KeySize = PdfEncryptionKeySize.Key256Bit;
[VB.NET]
doc.Security.KeySize = PdfEncryptionKeySize.Key256Bit 

Step 2: Encrypt PDF file by setting owner and user password. The password size you set should not be over the key size.

[C#]
doc.Security.OwnerPassword = "e-iceblue";
doc.Security.UserPassword = "pdfcomponent";
[VB.NET]
doc.Security.OwnerPassword = "e-iceblue"
doc.Security.UserPassword = "pdfcomponent" 

Step 3: Specify access restrictions of user password. There are nine permissions are available in the solution. You can see them as below picture.

Encrypt PDF Document

[C#]
doc.Security.Permissions = PdfPermissionsFlags.Print | PdfPermissionsFlags.CopyContent;
[VB.NET]
doc.Security.Permissions = PdfPermissionsFlags.Print Or PdfPermissionsFlags. CopyContent

After running your project, you will be requested a password when you open this encrypted PDF file. Please look at the effective screenshot below:

Encrypt PDF Document