Sample code for 30+ languages & platforms
Objective-C

Add a Private Key and Certificate Chain to a PFX

See more PFX/P12 Examples

Demonstrates Pfx.AddPrivateKey, which adds a private key together with its certificate chain to the PFX object.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. The chain must contain at least one certificate; the certificate at index 0 is treated as the leaf. The chain is built here with Cert.BuildCertChain.

Chilkat Objective-C Downloads

Objective-C
#import <CkoPfx.h>
#import <CkoPrivateKey.h>
#import <CkoCert.h>
#import <CkoCertChain.h>

BOOL success = NO;

CkoPfx *pfx = [[CkoPfx alloc] init];

//  The file path is relative to the application's current working directory.  An absolute path
//  may also be used.  Supply the path appropriate to your own environment.
//  Load the private key.
CkoPrivateKey *privKey = [[CkoPrivateKey alloc] init];
success = [privKey LoadPemFile: @"qa_data/private_key.pem"];
if (success == NO) {
    NSLog(@"%@",privKey.LastErrorText);
    return;
}

//  Load the certificate and build its chain of authority.  The chain must contain at least one
//  certificate; the certificate at index 0 is treated as the leaf.
CkoCert *cert = [[CkoCert alloc] init];
success = [cert LoadFromFile: @"qa_data/cert.pem"];
if (success == NO) {
    NSLog(@"%@",cert.LastErrorText);
    return;
}

CkoCertChain *chain = [[CkoCertChain alloc] init];
success = [cert BuildCertChain: chain];
if (success == NO) {
    NSLog(@"%@",cert.LastErrorText);
    return;
}

//  Add the private key and its certificate chain to the PFX.
success = [pfx AddPrivateKey: privKey certChain: chain];
if (success == NO) {
    NSLog(@"%@",pfx.LastErrorText);
    return;
}

NSLog(@"%@",@"Private key and certificate chain added to the PFX.");