3 Replies Latest reply: Aug 22, 2008 6:04 PM by jaisor
isanjeck Level 1 Level 1 (0 points)
Was anybody successfull in using those methods of the security framework for iphone?

Im getting a status error code -9809 and I have no clue of what it means as it is not defined in the list of OSStatus

+ (NSString *) encrypt:(NSString *)data
uint8_t *plainText = (unsigned char *)[data UTF8String];
size_t BLOCKSIZE = sizeof(plainText);
uint8_t cipherText[BLOCKSIZE];
size_t *cipherTextLen = &BLOCKSIZE;

OSStatus status = SecKeyEncrypt(publickey, kSecPaddingNone, plainText, BLOCKSIZE, cipherText, cipherTextLen);
if(status != errSecSuccess)
NSAssert1(0, @"Error: failed to encrypt data '%d'.", status);

return [[NSString alloc] initWithUTF8String:(char *)cipherText];

Mac OS X (10.5.3)
  • eric_nelson Level 1 Level 1 (0 points)
    I am experiencing the same error code. My encrypt works, but the decrypt fails, i.e:

    void testcrypt(void)
    SecKeyRef oPublicKey;
    SecKeyRef oPrivateKey;

    CFDictionaryRef myDictionary;

    CFTypeRef keys[2];
    CFTypeRef values[2];

    // Initialize dictionary of key params
    keys[0] = kSecAttrKeyType;
    values[0] = kSecAttrKeyTypeRSA;
    keys[1] = kSecAttrKeySizeInBits;
    int iByteSize = 1024;
    values[1] = CFNumberCreate( NULL, kCFNumberIntType, &iByteSize );
    myDictionary = CFDictionaryCreate( NULL, keys, values, sizeof(keys) / sizeof(keys[0]), NULL, NULL );

    // Generate keys
    OSStatus status = SecKeyGeneratePair( myDictionary, &oPublicKey, &oPrivateKey );
    if ( status != 0 )
    NSLog( @"SecKeyGeneratePair failed" );

    // Encrypt some data
    uint8_t* pPlainText = (uint8_t*)"This is a test";

    uint8_t aCipherText[1024];
    size_t iCipherLength = 1024;
    status = SecKeyEncrypt( oPublicKey, kSecPaddingPKCS1, pPlainText, strlen( (char*)pPlainText ) + 1, &aCipherText[0], &iCipherLength );
    if ( status != 0 )
    NSLog( @"SecKeyEncrypt failed" );

    // Decrypt the data
    uint8_t aPlainText[1024];
    size_t iPlainLength = 1024;
    status = SecKeyDecrypt( oPrivateKey, kSecPaddingPKCS1, &aCipherText[0], iCipherLength, &aPlainText[0], &iPlainLength );
    if ( status != 0 )
    NSLog( @"SecKeyDecrypt failed" );
  • gabrielpalomino Level 1 Level 1 (0 points)

    I'm trying to compile the code you posted on the emulator but I'm getting some compile errors, I have imported <Security/Security.h frameworks.
    Is that happening because I'm working just with the emulator and without the device ?
  • jaisor Level 1 Level 1 (0 points)
    I am just getting into this crypto stuff myself, but I got the above code to work when I used no padding - kSecPaddingNone

    I presume the padding is the system adding different type of hashing at the end of the buffers that the developer should use to ensure further data consistency.

    The code posted does not account for that and I think that is why it fails.

    Works great with kSecPaddingNone tho. Good job, saved me a lot of research.