"Encrypt string with certificate from p12 file"

Mon 14 June 2010

#import "NSDataAdditions.h"

 

@implementation Cryptography

 

const size_t BUFFER_SIZE = 240;

const size_t CIPHER_BUFFER_SIZE = 1024;

const uint32_t PADDING = kSecPaddingPKCS1;

 

- (NSString*) test1

{

    uint8_t *plainBuffer;

    uint8_t *decryptedBuffer;

    const char inputString[] = "some data";

    int len = strlen(inputString);

    

    plainBuffer = (uint8_t *)calloc(len, sizeof(uint8_t));

    

    strncpy( (char *)plainBuffer, inputString, len);

    

    

    NSString * path = [[NSBundle mainBundle] pathForResource:@"test1" ofType:@"p12"];

    assert(path != nil);

    

    NSData * data = [NSData dataWithContentsOfFile:path];

    assert(data != nil);

    

    

    CFArrayRef tmpCFArrayRef = CFArrayCreate(kCFAllocatorDefault, NULL, 0, NULL);//(CFArrayRef)items;

    

    NSMutableDictionary * options = [[NSMutableDictionary alloc] init];

// Set the public key query dictionary.

    [options setObject:@"some password for p12 file" forKey:(id)kSecImportExportPassphrase];

    SecPKCS12Import((CFDataRef) data, (CFDictionaryRef)options, &tmpCFArrayRef);

    

    NSMutableDictionary * items = (NSMutableDictionary*) [tmpCFArrayRef objectAtIndex:0];

    kCFAllocatorDefault, (const void **) &cert, 1, NULL);

    

    SecTrustRef trust = (SecTrustRef)[items objectForKey:(id)kSecImportItemTrust];

    

    pub_key_leaf = SecTrustCopyPublicKey(trust);

    int cipherBufferTotalSize = ceil(len/(float)BUFFER_SIZE)*256;

    uint8_t * cipherBuffer = (uint8_t *)calloc(cipherBufferTotalSize, sizeof(uint8_t));

    

    int procPlainBuffer = 0;

    int procCipherBuffer = 0;

    while (procPlainBuffer < len) {

        

        uint8_t * plainBufferChunc = (uint8_t *)calloc(BUFFER_SIZE, sizeof(uint8_t));

        uint8_t * cipherBufferChunc = (uint8_t *)calloc(256, sizeof(uint8_t));

        

        memcpy(plainBufferChunc, plainBuffer + procPlainBuffer, BUFFER_SIZE);

        

        [self encryptChunk :plainBufferChunc :cipherBufferChunc];

        procPlainBuffer += BUFFER_SIZE;

        

        memcpy(cipherBuffer + procCipherBuffer, cipherBufferChunc, 256);

        procCipherBuffer += 256;

        

        free(cipherBufferChunc);

        free(plainBufferChunc);

    }

    

    NSData* finalData = [[[NSData alloc] initWithBytes:cipherBuffer

                                                length:cipherBufferTotalSize] autorelease];

    

    NSString* retRes = [finalData base64Encoding];

    

    return retRes;

}