在Objective-C中以编程方式创建.pem文件?

时间:2013-02-07 00:26:44

标签: iphone objective-c openssl pem csr

我正在尝试使用Objective-C和iPhone应用程序中的OpenSSL库以编程方式从证书签名请求创建PEM文件。我按照Adria Navarro对这个问题的回答生成了CSR(类型X509_REQ *):

Generating an OpenSSL Certificate Signing Request in iOS with Keychain stored keys

我已通过将其打印到控制台确认CSR有效。

以下是我创建PEM文件的代码(CertificateSigningRequest.pem)。它最终创建一个空白文件(0个字节,没有文本)。我做错了什么,以至于它无法通过PEM_write_X509_REQ写入文件? (请注意,我是通过管理器下载应用程序文件夹来检查文件的。)

提前感谢您提供的任何帮助,如果我应该提供其他信息,请告知我们。

- (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"];
}

1 个答案:

答案 0 :(得分:4)

事实证明我的问题是我写完之后没有关闭文件。将最后一行添加到此方法就可以了。

- (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 =)
}