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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Google Cloud Document AI Basics
  • How to Convert Between PDF and TIFF in Java
  • Thumbnail Generator Microservice for PDF in Spring Boot
  • Python and Open-Source Libraries for Efficient PDF Management

Trending

  • Useful System Table Queries in Relational Databases
  • Simpler Data Transfer Objects With Java Records
  • Proactive Security in Distributed Systems: A Developer’s Approach
  • Is Big Data Dying?

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.6K 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

  • Google Cloud Document AI Basics
  • How to Convert Between PDF and TIFF in Java
  • Thumbnail Generator Microservice for PDF in Spring Boot
  • Python and Open-Source Libraries for Efficient PDF Management

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!