Skip to content
Guides

Encrypt and Protect PDF

This sample shows how to set user password and permission password, decrypt, set document permission.

objective-c
// Init Methods
- (instancetype)initWithDocument:(CPDFDocument *)document {
  CPDFDocument *myDocument = document;
  [self encryptByUserPassword:self.document];
  [self encryptByOwnerPassword:self.document];
  [self encryptByAllPasswords:self.document];
  [self unlock];
  [self decrypt];
}

// Document use RC4, AES128, AES256, NoEncryptAlgoencrypt done
- (void)encryptByUserPassword:(CPDFDocument *)oldDocument {
    NSString *commandLineStr = @"";
  
    {
        commandLineStr = [commandLineStr stringByAppendingString:@"-------------------------------------\n"];
        commandLineStr = [commandLineStr stringByAppendingString:@"Samples 1: Document use RC4 encrypt done\n"];
        
        // Get Sandbox path for saving the PDF File
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        NSString *writeDirectoryPath = [NSString stringWithFormat:@"%@/%@", path, @"Encrypt"];
  
        if (![[NSFileManager defaultManager] fileExistsAtPath:writeDirectoryPath])
            [[NSFileManager defaultManager] createDirectoryAtURL:[NSURL fileURLWithPath:writeDirectoryPath] withIntermediateDirectories:YES attributes:nil error:nil];
        NSString *writeFilePath = [NSString stringWithFormat:@"%@/%@.pdf",writeDirectoryPath,@"EncryptUserRC4Test"];
        
        // Save the document in the test PDF file
        NSURL *encryptUserRC4URL = [NSURL fileURLWithPath:writeFilePath];
        [oldDocument writeToURL:encryptUserRC4URL];
        
        // Create a new document for test PDF file
        CPDFDocument *document = [[CPDFDocument alloc] initWithURL:encryptUserRC4URL];
        
        // Set encryption attributes
        NSDictionary *options = @{CPDFDocumentUserPasswordOption : @"User",
                                  CPDFDocumentEncryptionLevelOption : @(CPDFDocumentEncryptionLevelRC4)};
        [document writeToURL:encryptUserRC4URL withOptions:options];
        
        commandLineStr = [commandLineStr stringByAppendingString:@"User password is: User\n"];
        scommandLineStr = [commandLineStr stringByAppendingString:@"Done. Results saved in EncryptUserRC4Test.pdf\n\n"];
    }
    
    {
        commandLineStr = [commandLineStr stringByAppendingString:@"-------------------------------------\n"];
        commandLineStr = [commandLineStr stringByAppendingString:@"Samples 2: Document use AES128 encrypt done\n"];
        
        // Get Sandbox path for saving the PDF File
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        NSString *writeDirectoryPath = [NSString stringWithFormat:@"%@/%@", path, @"Encrypt"];
      
        if (![[NSFileManager defaultManager] fileExistsAtPath:writeDirectoryPath])
            [[NSFileManager defaultManager] createDirectoryAtURL:[NSURL fileURLWithPath:writeDirectoryPath] withIntermediateDirectories:YES attributes:nil error:nil];
        NSString *writeFilePath = [NSString stringWithFormat:@"%@/%@.pdf",writeDirectoryPath,@"EncryptUserAES128Test"];
        
        // Save the document in the test PDF file
        NSURL *encryptUserAES128URL = [NSURL fileURLWithPath:writeFilePath];
        [oldDocument writeToURL:encryptUserAES128URL];
        
        // Create a new document for test PDF file
        CPDFDocument *document = [[CPDFDocument alloc] initWithURL:encryptUserAES128URL];
        
        // Set encryption attributes
        NSDictionary *options = @{CPDFDocumentUserPasswordOption : @"User",
                                  CPDFDocumentEncryptionLevelOption : @(CPDFDocumentEncryptionLevelAES128)};
        [document writeToURL:encryptUserAES128URL withOptions:options];
        
        commandLineStr = [commandLineStr stringByAppendingString:@"User password is: User\n"];
        commandLineStr = [commandLineStr stringByAppendingString:@"Done. Results saved in EncryptUserAES128Test.pdf\n\n"];
    }
    
    {
        commandLineStr = [commandLineStr stringByAppendingString:@"-------------------------------------\n"];
        commandLineStr = [commandLineStr stringByAppendingString:@"Samples 3: Document use AES256 encrypt done\n"];
        
        // Get Sandbox path for saving the PDF File
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        NSString *writeDirectoryPath = [NSString stringWithFormat:@"%@/%@", path, @"Encrypt"];
  
        if (![[NSFileManager defaultManager] fileExistsAtPath:writeDirectoryPath])
            [[NSFileManager defaultManager] createDirectoryAtURL:[NSURL fileURLWithPath:writeDirectoryPath] withIntermediateDirectories:YES attributes:nil error:nil];
        NSString *writeFilePath = [NSString stringWithFormat:@"%@/%@.pdf",writeDirectoryPath,@"EncryptUserAES256Test"];
        
        // Save the document in the test PDF file
        NSURL *encryptUserAES256URL = [NSURL fileURLWithPath:writeFilePath];
        [oldDocument writeToURL:encryptUserAES256URL];
        
        // Create a new document for test PDF file
        CPDFDocument *document = [[CPDFDocument alloc] initWithURL:encryptUserAES256URL];
        
        // Set encryption attributes
        NSDictionary *options = @{CPDFDocumentUserPasswordOption : @"User",
                                  CPDFDocumentEncryptionLevelOption : @(CPDFDocumentEncryptionLevelAES256)};
        [document writeToURL:encryptUserAES256URL withOptions:options];
        
        commandLineStr = [commandLineStr stringByAppendingString:@"User password is: User\n"];
        commandLineStr = [commandLineStr stringByAppendingString:@"Done. Results saved in EncryptUserAES256Test.pdf\n\n"];
    }
    
    {
        commandLineStr = [commandLineStr stringByAppendingString:@"-------------------------------------\n"];
        commandLineStr = [commandLineStr stringByAppendingString:@"Samples 4: Document use NoEncryptAlgo encrypt done\n"];
        
        // Get Sandbox path for saving the PDF File
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        NSString *writeDirectoryPath = [NSString stringWithFormat:@"%@/%@", path, @"Encrypt"];
    
        if (![[NSFileManager defaultManager] fileExistsAtPath:writeDirectoryPath])
            [[NSFileManager defaultManager] createDirectoryAtURL:[NSURL fileURLWithPath:writeDirectoryPath] withIntermediateDirectories:YES attributes:nil error:nil];
        NSString *writeFilePath = [NSString stringWithFormat:@"%@/%@.pdf",writeDirectoryPath,@"EncryptUserNoEncryptAlgoTest"];
        
        // Save the document in the test PDF file
        NSURL *encryptUserNoEncryptAlgoURL = [NSURL fileURLWithPath:writeFilePath];
        [oldDocument writeToURL:encryptUserNoEncryptAlgoURL];
        
        // Create a new document for test PDF file
        CPDFDocument *document = [[CPDFDocument alloc] initWithURL:encryptUserNoEncryptAlgoURL];
        
        // Set encryption attributes
        NSDictionary *options = @{CPDFDocumentUserPasswordOption : @"User",
                                  CPDFDocumentEncryptionLevelOption : @(CPDFDocumentEncryptionLevelNoEncryptAlgo)};
        [document writeToURL:encryptUserNoEncryptAlgoURL withOptions:options];
        
        commandLineStr = [commandLineStr stringByAppendingString:@"User password is: User\n"];
        commandLineStr = [commandLineStr stringByAppendingString:@"Done. Results saved in EncryptUserNoEncryptAlgoTest.pdf\n\n"];
    }
}

// Encrypt by owner password done
- (void)encryptByOwnerPassword:(CPDFDocument *)oldDocument {
    self.commandLineStr = [self.commandLineStr stringByAppendingString:@"-------------------------------------\n"];
    self.commandLineStr = [self.commandLineStr stringByAppendingString:@"Samples 5: Encrypt by owner password done\n"];
    
    // Get Sandbox path for saving the PDF File
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *writeDirectoryPath = [NSString stringWithFormat:@"%@/%@", path, @"Encrypt"];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:writeDirectoryPath])
        [[NSFileManager defaultManager] createDirectoryAtURL:[NSURL fileURLWithPath:writeDirectoryPath] withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *writeFilePath = [NSString stringWithFormat:@"%@/%@.pdf",writeDirectoryPath,@"EncryptOwnerRC4Test"];

    // Save the document in the test PDF file
    NSURL *encryptOwnerRC4URL = [NSURL fileURLWithPath:writeFilePath];
    [oldDocument writeToURL:encryptOwnerRC4URL];
    
    // Create a new document for test PDF file
    CPDFDocument *document = [[CPDFDocument alloc] initWithURL:encryptOwnerRC4URL];
    [self.userPasswordURLs addObject:encryptOwnerRC4URL];
    
    // Set encryption attributes
    NSDictionary *options = @{CPDFDocumentUserPasswordOption : @"User",
                              CPDFDocumentOwnerPasswordOption : @"Owner",
                              CPDFDocumentEncryptionLevelOption : @(CPDFDocumentEncryptionLevelRC4),
                              CPDFDocumentAllowsPrintingOption : @(NO),
                              CPDFDocumentAllowsCopyingOption : @(NO),};
    [document writeToURL:encryptOwnerRC4URL withOptions:options];
    
    self.commandLineStr = [self.commandLineStr stringByAppendingString:@"Owner password is: Owner\n"];
    self.commandLineStr = [self.commandLineStr stringByAppendingString:@"Done. Results saved in EncryptOwnerRC4Test.pdf\n\n"];
}

// Encrypt by Both user and owner passwords done
- (void)encryptByAllPasswords:(CPDFDocument *)oldDocument {
  NSString *commandLineStr = @"";
  
    commandLineStr = [commandLineStr stringByAppendingString:@"-------------------------------------\n"];
    commandLineStr = [commandLineStr stringByAppendingString:@"Samples 6: Encrypt by Both user and owner passwords done\n"];
    
    // Get Sandbox path for saving the PDF File
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *writeDirectoryPath = [NSString stringWithFormat:@"%@/%@", path, @"Encrypt"];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:writeDirectoryPath])
        [[NSFileManager defaultManager] createDirectoryAtURL:[NSURL fileURLWithPath:writeDirectoryPath] withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *writeFilePath = [NSString stringWithFormat:@"%@/%@.pdf",writeDirectoryPath,@"EncryptAllAES256Test"];
    
    // Save the document in the test PDF file
    NSURL *encryptAllAES256URL = [NSURL fileURLWithPath:writeFilePath];
    [oldDocument writeToURL:encryptAllAES256URL];
    
    // Create a new document for test PDF file
    CPDFDocument *document = [[CPDFDocument alloc] initWithURL:encryptAllAES256URL];
    
    // Set encryption attributes
    NSDictionary *options = @{CPDFDocumentOwnerPasswordOption : @"Owner",
                              CPDFDocumentUserPasswordOption : @"User",
                              CPDFDocumentEncryptionLevelOption : @(CPDFDocumentEncryptionLevelAES256),
                              CPDFDocumentAllowsPrintingOption : @(YES),
                              CPDFDocumentAllowsHighQualityPrintingOption : @(NO),
                              CPDFDocumentAllowsCopyingOption : @(NO),
                              CPDFDocumentAllowsDocumentChangesOption : @(NO),
                              CPDFDocumentAllowsDocumentAssemblyOption : @(NO),
                              CPDFDocumentAllowsCommentingOption : @(NO),
                              CPDFDocumentAllowsFormFieldEntryOption : @(NO)};
    [document writeToURL:encryptAllAES256URL withOptions:options];
    
    commandLineStr = [commandLineStr stringByAppendingString:@"User password is: User\n"];
    commandLineStr = [commandLineStr stringByAppendingString:@"Owner password is: Owner\n"];
    commandLineStr = [commandLineStr stringByAppendingString:@"Done. Results saved in EncryptAllAES256Test.pdf\n\n"];
}

//  Unlock with owner password and user password
- (void)unlock {
  NSString *commandLineStr = @"";
  
    commandLineStr = [commandLineStr stringByAppendingString:@"-------------------------------------\n"];
    commandLineStr = [commandLineStr stringByAppendingString:@"Samples 7: Unlock with owner password and user password\n"];
    
    // Get Sandbox path for saving the PDF File
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *writeDirectoryPath = [NSString stringWithFormat:@"%@/%@", path, @"Encrypt"];
    NSString *documentFolder = [[NSBundle mainBundle] pathForResource:@"AllPasswords" ofType:@"pdf"];
    
    // Copy file
    if (![[NSFileManager defaultManager] fileExistsAtPath:writeDirectoryPath])
        [[NSFileManager defaultManager] createDirectoryAtURL:[NSURL fileURLWithPath:writeDirectoryPath] withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *writeFilePath = [NSString stringWithFormat:@"%@/%@.pdf",writeDirectoryPath,@"unlockAllPasswords"];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:documentFolder])
        [[NSFileManager defaultManager] copyItemAtURL:[NSURL fileURLWithPath:documentFolder] toURL:[NSURL fileURLWithPath:writeFilePath] error:nil];
    
    // Unlock the document and print document permission information
    // It is worth noting that the document is only unlocked, not decrypted, and the password is still required for the next opening
    NSURL *unlockAllPasswordsURL = [NSURL fileURLWithPath:writeFilePath];
    CPDFDocument *document = [[CPDFDocument alloc] initWithURL:unlockAllPasswordsURL];
    
    [document unlockWithPassword:@"Owner"];
    
    commandLineStr = [commandLineStr stringByAppendingFormat:@"AllowsPrinting:%@\n", document.allowsPrinting ? @"YES" :  @"NO"];
    commandLineStr = [commandLineStr stringByAppendingFormat:@"AllowsHighQualityPrinting:%@\n", document.allowsHighQualityPrinting ? @"YES" :  @"NO"];
    commandLineStr = [commandLineStr stringByAppendingFormat:@"AllowsCopying:%@\n", document.allowsCopying ? @"YES" :  @"NO"];
    commandLineStr = [commandLineStr stringByAppendingFormat:@"AllowsDocumentChanges:%@\n", document.allowsDocumentChanges ? @"YES" :  @"NO"];
    commandLineStr = [commandLineStr stringByAppendingFormat:@"AllowsDocumentAssembly:%@\n", document.allowsDocumentAssembly ? @"YES" :  @"NO"];
    commandLineStr = [commandLineStr stringByAppendingFormat:@"AllowsCommenting:%@\n", document.allowsPrinting ? @"YES" :  @"NO"];
    commandLineStr = [commandLineStr stringByAppendingFormat:@"AllowsFormFieldEntry:%@\n\n", document.allowsFormFieldEntry ? @"YES" :  @"NO"];
}

// Decrypt with owner password and user password
- (void)decrypt {
    NSString *commandLineStr = @"";
  
    commandLineStr = [commandLineStr stringByAppendingString:@"-------------------------------------\n"];
    commandLineStr = [commandLineStr stringByAppendingString:@"Samples 8: Decrypt with owner password and user password\n"];
    
    // Get Sandbox path for saving the PDF File
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *writeDirectoryPath = [NSString stringWithFormat:@"%@/%@", path, @"Encrypt"];
    NSString *documentFolder = [[NSBundle mainBundle] pathForResource:@"AllPasswords" ofType:@"pdf"];
    
    // Copy file
    if (![[NSFileManager defaultManager] fileExistsAtPath:writeDirectoryPath])
        [[NSFileManager defaultManager] createDirectoryAtURL:[NSURL fileURLWithPath:writeDirectoryPath] withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *writeFilePath = [NSString stringWithFormat:@"%@/%@.pdf",writeDirectoryPath,@"DecryptAllPasswordsTest"];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:documentFolder])
        [[NSFileManager defaultManager] copyItemAtURL:[NSURL fileURLWithPath:documentFolder] toURL:[NSURL fileURLWithPath:writeFilePath] error:nil];
    
    // Decrypt document
    NSURL *decryptAllPasswordsURL = [NSURL fileURLWithPath:writeFilePath];
    CPDFDocument *document = [[CPDFDocument alloc] initWithURL:decryptAllPasswordsURL];
    
    [document unlockWithPassword:@"Owner"];
    [document writeDecryptToURL:decryptAllPasswordsURL];
    
    commandLineStr = [commandLineStr stringByAppendingString:@"Done. Results saved in DecryptAllPasswordsTest.pdf\n\n"];
}