DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Document Generation API: How to Automate Personalized Document Creation at Scale
  • Extracting Clean Excel Tables From PDFs Using Python + Docling
  • Why Whole-Document Sentiment Analysis Fails and How Section-Level Scoring Fixes It
  • Google Cloud Document AI Basics

Trending

  • Give Your AI Assistant Long-Term Memory With perag
  • The Cross-Lingual RAG Problem Nobody Is Talking About
  • The ORM Is Over: AI-Written SQL Is the New Data Access Layer
  • From printTriangularNumber to Duff’s Device: Mastering Java Switch Statements Old and New

How to Detect If Source PDF File is Password Protected or Not inside .NET Apps

By 
David Zondray user avatar
David Zondray
·
Jan. 28, 15 · Code Snippet
Likes (0)
Comment
Save
Tweet
Share
6.8K Views

Join the DZone community and get the full member experience.

Join For Free
This technical tip shows how .NET developers can determine if the source PDF file is password protected  or not inside their .NET applications using Aspose.Pdf for .NET. Aspose.Pdf for .NET provides great capabilities of dealing with PDF documents. When using Document class of Aspose.Pdf namespace to open a PDF document which is password protected, we need to provide the password information as an argument to Document constructor and in case this information is not provided, an error message is generated. In fact when trying to open a PDF file with Document object, the constructor is trying to read the contents of PDF file and in case correct password is not provided, an error message is generated (it happens to prevent unauthorized access of document). When dealing with encrypted PDF files, you may come across the scenario where you would be interested to detect if a PDF has an open password and/or an edit password. Sometimes there are documents which do not require password information while opening them, but they require information in order to edit the contents of file. So in order to fulfill the above requirements, PdfFileInfo class present under Aspose.Pdf.Facades provides the properties which can help in determining the required information.
//C# Code Sample

// load the source PDF document
PdfFileInfo fileInfo = new PdfFileInfo(@"D:\PDF_OpenPassword.pdf");
// determine that source PDF file is Encrypted with password
bool encrypted = fileInfo.IsEncrypted;
// MessageBox displays the current status related to PDf encryption
MessageBox.Show(encrypted.ToString());

//VB.NET Code Sample

' load the source PDF document
Dim fileInfo As PdfFileInfo = New PdfFileInfo("D:\PDF_OpenPassword.pdf")
' determine that source PDF file is Encrypted with password
Dim encrypted As Boolean = fileInfo.IsEncrypted
' MessageBox displays the current status related to PDf encryption
MessageBox.Show(encrypted.ToString())

//Get information about PDF document security

PdfFileInfo contains three properties to get information about PDF document security.

//C# Code Sample

PdfFileInfo fileInfo = new PdfFileInfo(TestSettings.GetInputFile("PdfWithNoOpenPasswordAndPermPassword.pdf"));
Assert.True(fileInfo.IsEncrypted);
Assert.AreEqual(PasswordType.User, fileInfo.PasswordType);
fileInfo = new PdfFileInfo(TestSettings.GetInputFile("PdfWithNoOpenPasswordAndPermPassword.pdf"), "password");
Assert.True(fileInfo.IsEncrypted);
Assert.AreEqual(PasswordType.Owner, fileInfo.PasswordType);
Assert.False(fileInfo.HasOpenPassword);
Assert.True(fileInfo.HasEditPassword);

fileInfo = new PdfFileInfo(TestSettings.GetInputFile("PdfWithOpenPasswordAndNoPermPassword.pdf"));
Assert.True(fileInfo.IsEncrypted);
Assert.AreEqual(PasswordType.Inaccessible, fileInfo.PasswordType);
Assert.True(fileInfo.HasOpenPassword);
try
{
  bool hasOwnerPassword = fileInfo.HasEditPassword;
  Assert.Fail("When PasswordType is Inaccessible we can't read HasEditPassword property.");
}
catch (InvalidPasswordException e)
{
  // right what we expect
}
fileInfo = new PdfFileInfo(TestSettings.GetInputFile("PdfWithOpenPasswordAndNoPermPassword.pdf"), "password");
Assert.True(fileInfo.IsEncrypted);
Assert.AreEqual(PasswordType.User, fileInfo.PasswordType);
Assert.True(fileInfo.HasOpenPassword);
Assert.False(fileInfo.HasEditPassword);

fileInfo = new PdfFileInfo(TestSettings.GetInputFile("PdfWithOpenPasswordAndPermPassword.pdf"));
Assert.True(fileInfo.IsEncrypted);
Assert.AreEqual(PasswordType.Inaccessible, fileInfo.PasswordType);
Assert.True(fileInfo.HasOpenPassword);
try
{
  bool hasOwnerPassword = fileInfo.HasEditPassword;
  Assert.Fail("When PasswordType is Inaccessible we can't read HasEditPassword property.");
}
catch (InvalidPasswordException e)
{
  // right what we expect
}

fileInfo = new PdfFileInfo(TestSettings.GetInputFile("PdfWithOpenPasswordAndPermPassword.pdf"), "password1");
Assert.True(fileInfo.IsEncrypted);
Assert.AreEqual(PasswordType.User, fileInfo.PasswordType);
Assert.True(fileInfo.HasOpenPassword);
Assert.True(fileInfo.HasEditPassword);
fileInfo = new PdfFileInfo(TestSettings.GetInputFile("PdfWithOpenPasswordAndPermPassword.pdf"), "password2");
Assert.True(fileInfo.IsEncrypted);
Assert.AreEqual(PasswordType.Owner, fileInfo.PasswordType);
Assert.True(fileInfo.HasOpenPassword);
Assert.True(fileInfo.HasEditPassword);

//Determine correct password from Array

//Sometimes there is a requirement to determine the correct password from array of passwords and open the document with correct password. The following code snippet demonstrates the steps to iterate through the array of passwords and try opening the document with correct password.

//C# Code Sample

// load source PDF file
PdfFileInfo info = new PdfFileInfo();
info.BindPdf("c:/pdftest/Lorem+Ipsum_protected.pdf");
// determine if the source PDF is encrypted
Console.WriteLine("File is password protected " + info.IsEncrypted);
String[] passwords = new String[5]{"test","test1","test2","test3","sample"};
for (int passwordcount = 0; passwordcount < passwords.Length; passwordcount++)
{
    try
    {
        Document doc = new Document("c:/pdftest/Lorem+Ipsum_protected.pdf", passwords[passwordcount]);
        if (doc.Pages.Count>0)
            Console.WriteLine("Number of Page in document are = "+doc.Pages.Count);
    }
    catch (Aspose.Pdf.Exceptions.InvalidPasswordException)
    {
        Console.WriteLine("Password = "+passwords[passwordcount]+ "  is not correct");
    }
}

//VB.NET Code Sample

' load source PDF file
Dim info As PdfFileInfo = New PdfFileInfo()
info.BindPdf("c:/pdftest/Lorem+Ipsum_protected.pdf")
' determine if the source PDF is encrypted
Console.WriteLine("File is password protected " & info.IsEncrypted)
Dim passwords() = New String() {"test", "test1", "test2", "test3", "sample"}
For passwordcount As Integer = 0 To passwords.Length - 1
    Try
        Dim doc As Document = New Document("c:/pdftest/Lorem+Ipsum_protected.pdf", passwords(passwordcount))
        If (doc.Pages.Count > 0) Then
            Console.WriteLine("Number of Page in document are = " & doc.Pages.Count)
        End If
    Catch ex As Aspose.Pdf.Exceptions.InvalidPasswordException
        Console.WriteLine("Password = " & passwords(passwordcount) & "  is not correct")
    End Try
Next
End Sub
PDF

Opinions expressed by DZone contributors are their own.

Related

  • Document Generation API: How to Automate Personalized Document Creation at Scale
  • Extracting Clean Excel Tables From PDFs Using Python + Docling
  • Why Whole-Document Sentiment Analysis Fails and How Section-Level Scoring Fixes It
  • Google Cloud Document AI Basics

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook