Eric Eric - 10 months ago 87
Swift Question

How to programmatically enter a password inside a password protected PDF file?

I am making a os x application in swift that can programmatically 'crack' a password by trying each number from 1-99999999. I know the location of the PDF file in string format. How can I,

  1. Test if the PDF file is password protected?

  2. If it is, try if a password is correct?

Thanks for helping me!
(It is just for learning purposes not for real hacking;) )


I found the answer I was looking for on this apple site. Here is how I managed to get it work:

  1. first you transform the filepath string into NSURL(and make CFURL of that) like this:

    let path : NSString = filepath as NSString        
    let thePath = path.stringByExpandingTildeInPath   
    let url = NSURL.fileURLWithPath(thePath)   
    let CFUrl = url as CFURL
  2. You import CoreGraphics and CoreFoundation and then make a document like this:

    var document : CGPDFDocumentRef = CGPDFDocumentCreateWithURL(CFUrl)
  3. Now you can use the CoreGraphics methods to check if it is unlocked or not and to enter a password like this:

    if CGPDFDocumentIsUnlocked(document) {
        //true if there is NO password   
    if CGPDFDocumentUnlockWithPassword(document, "password here") {      
        //returns true if the password is correct