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
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • A PDF Framework That Solves the Pain Points of Enterprise Development
  • How To Create and Edit PDF Annotations in Java
  • Alternatives to Handsontable and ag-Grid
  • Template-Based PDF Document Generation in Java

Trending

  • API Design
  • Exploring Sorting Algorithms: A Comprehensive Guide
  • A Better Web3 Experience: Account Abstraction From Flow (Part 2)
  • DevSecOps: Integrating Security Into Your DevOps Workflow

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

David Zondray user avatar by
David Zondray
·
Jan. 28, 15 · Code Snippet
Like (0)
Save
Tweet
Share
6.08K 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

  • A PDF Framework That Solves the Pain Points of Enterprise Development
  • How To Create and Edit PDF Annotations in Java
  • Alternatives to Handsontable and ag-Grid
  • Template-Based PDF Document Generation in Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: