Creating a .pem file programmatically in Objective-C?

I am trying to create a PEM file programmatically from a certificate signing request using Objective-C and the OpenSSL library in an iPhone app. I created a CSR (of type X509_REQ *) following Adria Navarro on this question:

Create an iOS OpenSSL Certificate Signing Request with Stored Keychain Keys

I have verified that the CSR is valid by printing it to the console.

Below is my code for generating a PEM file (CertificateSigningRequest.pem). This creates an empty file (0 bytes and no text). Am I doing something wrong so that it cannot write to the file via PEM_write_X509_REQ? (Note that I check the file by uploading the app folder through the Organizer.)

Thanks in advance for any help you can provide and let me know if I should provide more information.

- (void)createPemFileWithCertificateSigningRequest:(X509_REQ *)certSigningRequest
{
    //delete existing PEM file if there is one
    [self deletePemFile];

    //create empty PEM file
    NSString *pemFilePath = [self pemFilePath];
    if (![[NSFileManager defaultManager] createFileAtPath:pemFilePath contents:nil attributes:nil])
    {
        NSLog(@"Error creating file for PEM");
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error creating file for PEM" message:[NSString stringWithFormat:@"Could not create file at the following location:\n\n%@", pemFilePath] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
        return;
    }

    //get a FILE struct for the PEM file
    NSFileHandle *outputFileHandle = [NSFileHandle fileHandleForWritingAtPath:pemFilePath];
    FILE *pemFile = fdopen([outputFileHandle fileDescriptor], "w");

    //write the CSR to the PEM file
    PEM_write_X509_REQ(pemFile, certSigningRequest);
}

- (NSString *)pemFilePath
{
    NSString *documentsFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    return [documentsFolder stringByAppendingPathComponent:@"CertificateSigningRequest.pem"];
}

      

+3


source to share


1 answer


It turns out my problem was that I didn't close the file after I wrote it. Adding a final line to this method did the trick.



- (void)createPemFileWithCertificateSigningRequest:(X509_REQ *)certSigningRequest
{
    //...

    //write the CSR to the PEM file
    PEM_write_X509_REQ(pemFile, certSigningRequest);

    //close the file
    fclose(pemFile); //THIS MAKES EVERYTHING WORK =)
}

      

+4


source







All Articles