Sample code for 30+ languages & platforms
Objective-C

RSA Encrypt Randomly Generated AES Key

See more RSA Examples

Demonstrates how to RSA encrypt a randomly generated AES key.

Chilkat Objective-C Downloads

Objective-C
#import <CkoPrng.h>
#import <CkoBinData.h>
#import <CkoCert.h>
#import <CkoPublicKey.h>
#import <CkoRsa.h>
#import <NSString.h>

BOOL success = NO;

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

// First generate a 256-bit AES key (32 bytes).
CkoPrng *prng = [[CkoPrng alloc] init];
CkoBinData *bdAesKey = [[CkoBinData alloc] init];
success = [prng GenRandomBd: [NSNumber numberWithInt: 32] bd: bdAesKey];

// Use a public key from a certificate for RSA encryption.
CkoCert *cert = [[CkoCert alloc] init];

success = [cert LoadFromFile: @"qa_data/pem/mf_public_rsa.pem"];
if (success == NO) {
    NSLog(@"%@",cert.LastErrorText);
    return;
}

CkoPublicKey *pubKey = [[CkoPublicKey alloc] init];
[cert GetPublicKey: pubKey];

CkoRsa *rsa = [[CkoRsa alloc] init];
success = [rsa UsePublicKey: pubKey];
if (success == NO) {
    NSLog(@"%@",rsa.LastErrorText);
    return;
}

// RSA encrypt our 32-byte AES key.
// The contents of bdAesKey are replaced with result of the RSA encryption.
success = [rsa EncryptBd: bdAesKey usePrivateKey: NO];
if (success == NO) {
    NSLog(@"%@",rsa.LastErrorText);
    return;
}

// Return the result as a base64 string
NSString *encryptedAesKey = [bdAesKey GetEncoded: @"base64"];

NSLog(@"%@%@",@"encrypted AES key = ",encryptedAesKey);