Encrypt and decrypt PDF files in C++
Contents
[
Hide
]
Encrypt a PDF with passwords
- Open the input PDF as a Document.
- Select Permissions::ExtractContent and CryptoAlgorithm::AESx128.
- Call Encrypt() with the sample user and owner passwords.
- Save the PDF with Save().
#include <system/exceptions.h>
#include <Aspose.PDF.Cpp/Document.h>
#include <Aspose.PDF.Cpp/Permissions.h>
#include <Aspose.PDF.Cpp/Security/CryptoAlgorithm.h>
using namespace System;
using namespace Aspose::Pdf;
namespace SecuringAndSigningExamples {
void EncryptPdfFile(System::String inputFile, System::String outputFile)
{
auto document = MakeObject<Document>(inputFile);
document->Encrypt(u"user", u"owner", Permissions::ExtractContent, CryptoAlgorithm::AESx128);
document->Save(outputFile);
}
} // namespace SecuringAndSigning
Set document privileges
- Open the input PDF as a Document.
- Start with DocumentPrivilege::get_ForbidAll().
- Enable AllowScreenReaders.
- Call Encrypt() with the passwords, privileges, AESx128, and false for encryptMetadata.
- Save the PDF with Save().
#include <system/exceptions.h>
#include <Aspose.PDF.Cpp/Document.h>
#include <Aspose.PDF.Cpp/Facades/DocumentPrivilege.h>
#include <Aspose.PDF.Cpp/Security/CryptoAlgorithm.h>
using namespace System;
using namespace Aspose::Pdf;
using namespace Aspose::Pdf::Facades;
namespace SecuringAndSigningExamples {
void SetPrivilegesOnExistingPdfFile(System::String inputFile, System::String outputFile)
{
{
auto document = MakeObject<Document>(inputFile);
auto documentPrivilege = DocumentPrivilege::get_ForbidAll();
documentPrivilege->set_AllowScreenReaders(true);
document->Encrypt(u"user", u"owner", documentPrivilege, CryptoAlgorithm::AESx128, false);
document->Save(outputFile);
}
}
} // namespace SecuringAndSigning
Decrypt a PDF
The literal password must match the input PDF. The explicit System::String selects the password constructor overload.
- Open the Document using the sample password wrapped in System::String.
- Call Decrypt().
- Save the PDF with Save().
#include <system/exceptions.h>
#include <Aspose.PDF.Cpp/Document.h>
using namespace System;
using namespace Aspose::Pdf;
namespace SecuringAndSigningExamples {
void DecryptPdfFile(System::String inputFile, System::String outputFile)
{
auto document = MakeObject<Document>(inputFile, String(u"password"));
document->Decrypt();
document->Save(outputFile);
}
} //namespace SecuringAndSigning
Change user and owner passwords
- Open the Document with the existing owner password.
- Call ChangePasswords() with the old owner password and the new user and owner passwords.
- Save the PDF with Save().
#include <system/exceptions.h>
#include <Aspose.PDF.Cpp/Document.h>
using namespace System;
using namespace Aspose::Pdf;
namespace SecuringAndSigningExamples {
void ChangePassword(System::String inputFile, System::String outputFile)
{
auto document = MakeObject<Document>(inputFile, String(u"owner"));
document->ChangePasswords(u"owner", u"newuser", u"newowner");
document->Save(outputFile);
}
} // namespace SecuringAndSigning
Test a fixed list of passwords
This sample logs candidate passwords. Its broad exception handler labels every caught System::Exception as an incorrect password, even when another error caused the failure.
- Create PdfFileInfo, print IsEncrypted, and close the facade.
- Iterate through the supplied password candidates.
- Attempt to open the Document with each candidate.
- Print the successful password and page count when at least one page is available.
- Catch System::Exception and continue to the next candidate.
#include <iostream>
#include <system/exceptions.h>
#include <Aspose.PDF.Cpp/Document.h>
#include <Aspose.PDF.Cpp/Facades/PdfFileInfo.h>
#include <Aspose.PDF.Cpp/Page.h>
#include <Aspose.PDF.Cpp/PageCollection.h>
using namespace System;
using namespace Aspose::Pdf;
using namespace Aspose::Pdf::Facades;
namespace SecuringAndSigningExamples {
void DetermineCorrectPasswordFromArray(System::String inputFile)
{
auto pdfFileInfo = MakeObject<PdfFileInfo>(inputFile);
{
std::cout << "File is password protected " << pdfFileInfo->get_IsEncrypted() << std::endl;
pdfFileInfo->Close();
}
const String passwords[] = { u"test", u"test1", u"test2", u"test3", u"sample" };
for (const auto& password : passwords) {
try {
auto document = MakeObject<Document>(inputFile, password);
if (document->get_Pages()->get_Count() > 0) {
std::cout << "Password = " << password << " is correct" << std::endl;
std::cout << "Number of pages in document = " << document->get_Pages()->get_Count() << std::endl;
break;
}
}
catch (const System::Exception&) {
std::cout << "Password = " << password << " is not correct" << std::endl;
}
}
}
} // namespace SecuringAndSigning
Password encryption in the PubSecEncryption sample
Despite its name, this function does not perform public-key encryption. The certificate parameters are only printed; they are not used to encrypt or decrypt the PDF.
- Create a Document with metadata and a text page.
- Call Encrypt() with user and owner passwords, PrintDocument permissions, and the supplied algorithm.
- Save the PDF with Save().
- Reopen the output with the user password and print its metadata and extracted text.
- Call Decrypt() and save pubsec_decrypted_out.pdf.
- Print the certificate filenames and sample password.
#include <Aspose.PDF.Cpp/Document.h>
#include <Aspose.PDF.Cpp/DocumentInfo.h>
#include <Aspose.PDF.Cpp/Generator/Paragraphs.h>
#include <Aspose.PDF.Cpp/Page.h>
#include <Aspose.PDF.Cpp/PageCollection.h>
#include <Aspose.PDF.Cpp/Permissions.h>
#include <Aspose.PDF.Cpp/Security/CertificateEncryptionOptions.h>
#include <Aspose.PDF.Cpp/Text/TextAbsorber.h>
#include <Aspose.PDF.Cpp/Text/TextFragment.h>
#include <iostream>
#include <system/collections/list.h>
#include <system/exceptions.h>
#include <system/io/file.h>
#include <system/io/path.h>
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Security::Cryptography::X509Certificates;
using namespace Aspose::Pdf;
using namespace Aspose::Pdf::Security;
using namespace Aspose::Pdf::Text;
namespace SecuringAndSigningExamples {
void PubSecEncryption(CryptoAlgorithm cryptoAlgorithm, System::String publicCertificate, System::String inputPfx, System::String outputFile)
{
const String pfxPassword = u"12345";
auto publicCert = MakeObject<X509Certificate2>(System::IO::File::ReadAllBytes(publicCertificate));
auto recipientCertificates = MakeObject<List<SharedPtr<X509Certificate2>>>();
recipientCertificates->Add(publicCert);
{
auto document = MakeObject<Document>();
document->get_Info()->set_Title(u"TestTitle");
document->get_Info()->set_Author(u"TestAuthor");
auto page = document->get_Pages()->Add();
page->get_Paragraphs()->Add(MakeObject<TextFragment>(u"Hello World!"));
document->Encrypt(Permissions::PrintDocument, cryptoAlgorithm, recipientCertificates);
document->Save(outputFile);
}
{
auto certOptions = MakeObject<CertificateEncryptionOptions>(publicCertificate, inputPfx, pfxPassword);
auto document = MakeObject<Document>(outputFile, certOptions);
std::cout << document->get_Info()->get_Title() << std::endl;
std::cout << document->get_Info()->get_Author() << std::endl;
auto textAbsorber = MakeObject<TextAbsorber>();
document->get_Pages()->idx_get(1)->Accept(textAbsorber);
std::cout << textAbsorber->get_Text() << std::endl;
document->Save(System::IO::Path::Combine(System::IO::Path::GetDirectoryName(outputFile), u"pubsec_decrypted_out.pdf"));
}
std::cout << "Used certificate files: "
<< System::IO::Path::GetFileName(publicCertificate)
<< ", " << System::IO::Path::GetFileName(inputPfx)
<< " with password " << pfxPassword << std::endl;
}
} // namespace SecuringAndSigningExamples