Question

I am trying to encrypt NSData with the following method:

- (NSData *) encryptWithData:(NSData *)content {

size_t plainLen = [content length];

void *plain = malloc(plainLen);
[content getBytes:plain
           length:plainLen];

size_t cipherLen = 256;
void *cipher = malloc(cipherLen);

OSStatus returnCode = SecKeyEncrypt("PUBLIC KEY HERE", kSecPaddingPKCS1, plain,
                                    plainLen, cipher, &cipherLen);

NSData *result = nil;
if (returnCode != 0) {
    NSLog(@"SecKeyEncrypt fail. Error Code: %ld", returnCode);
}
else {
    result = [NSData dataWithBytes:cipher
                            length:cipherLen];
}

free(plain);
free(cipher);

return result;

}

Where it is written "PUBLIC KEY HERE" I want to load an existing public key I already copied to my bundle. How can I do that?

Was it helpful?

Solution

For example use a certificate file which contains a public key:

NSData *certificateData = [NSData dataWithContentsOfURL:certificateURL options:0 error:&error];
if (certificateData) {
    SecCertificateRef certificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certificateData));
    // ...
    SecKeyRef publicKey;
    SecCertificateCopyPublicKey(certificate, &publicKey);
    // ...
}

To load data from the bundle:

NSArray *certificateURLs = [[NSBundle mainBundle] URLsForResourcesWithExtension:@"cer" subdirectory:@"myCertificates"];
for (NSURL *certificateURL in certificateURLs) {
    NSData *certificateData = [NSData dataWithContentsOfURL:certificateURL options:0 error:&error];
    // ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top