本文介绍了在Objective-C中以编程方式创建.pem文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 have generated the CSR (of type X509_REQ *) by following Adria Navarro's answer to this question:

生成OpenSSL证书签名在iOS中使用钥匙串存储的密钥进行请求

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

I've confirmed that the CSR is valid by printing it out to the console.

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

Below is my code for creating the PEM file (CertificateSigningRequest.pem). It ends up creating a blank file (0 bytes and no text). Am I doing something wrong, such that it is not able to write to the file via PEM_write_X509_REQ? (Note that I'm checking the file by downloading the app folder via Organizer.)

在此先感谢您可以提供的任何帮助,并让我知道是否应该提供其他信息.

Thanks in advance for any help you can provide, and let me know if I should provide additional info.

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

推荐答案

事实证明,我的问题是在写入文件后我没有关闭文件.在此方法中添加最后一行即可达到目的.

It turns out that my issue was that I wasn't closing the file after writing to it. Adding the 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 =)
}

这篇关于在Objective-C中以编程方式创建.pem文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 12:40