Sample code for 30+ languages & platforms
Objective-C

Generate an RSA Key and Save to Encrypted PEM

See more RSA Examples

Demonstrates how to generate an RSA key and save to an encrypted PEM file.

Chilkat Objective-C Downloads

Objective-C
#import <CkoRsa.h>
#import <CkoPrivateKey.h>
#import <NSString.h>
#import <CkoPublicKey.h>

BOOL success = NO;

CkoRsa *rsa = [[CkoRsa alloc] init];

//  Generate a 2048-bit key.
CkoPrivateKey *privKey = [[CkoPrivateKey alloc] init];
success = [rsa GenKey: [NSNumber numberWithInt: 2048] privKey: privKey];
if (success == NO) {
    NSLog(@"%@",rsa.LastErrorText);
    return;
}

NSString *password = @"secret";
//  Saving to a relative path (from the current working directory of the process).
NSString *path = @"rsaKeys/myTestRsaPrivate.pem";
//  Encrypt the PEM using 256-bit AES encryption.
privKey.Pkcs8EncryptAlg = @"aes256";
success = [privKey SavePkcs8EncryptedPemFile: password path: path];
if (success == NO) {
    NSLog(@"%@",privKey.LastErrorText);
    return;
}

//  image

//  We can also save the public key.
//  There is no need to encrypt public keys.
CkoPublicKey *pubKey = [[CkoPublicKey alloc] init];
[privKey ToPublicKey: pubKey];

path = @"rsaKeys/myTestRsaPublic.pem";
//  Choose PKCS1 or PKCS8
//  We'll choose PKCS8.
BOOL preferPkcs1 = NO;
success = [pubKey SavePemFile: preferPkcs1 path: path];
if (success == NO) {
    NSLog(@"%@",pubKey.LastErrorText);
    return;
}

//  image

NSLog(@"%@",@"Success.");