Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

Using SecKeyEncrypt/SecKeyDecrypt

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)

Posted on Jun 12, 2008 12:14 PM

Reply
3 replies

Jul 10, 2008 2:20 PM in response to isanjeck

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" );
}

Aug 22, 2008 6:04 PM in response to eric_nelson

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.

Using SecKeyEncrypt/SecKeyDecrypt

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple ID.