2

I want to store a symmetric key in the keychain of OS X. I read by the Apple DevDocs that I should use SecItemAdd in order to do this. I also read the CryptoExercise without any solutions for Me.
But when I'm doing so, I always got OSStatus

errSecNoSuchAttr (-25303).

Codesnippet as follows:

//Labels and app tags
NSString *label = @"My Testkey";
NSData * peerTag = [[NSData alloc] initWithBytes:(const void *)[label UTF8String] length:[label length]];

// Generating testkey
NSMutableData *key = [NSMutableData dataWithLength:kCCKeySizeAES128];
SecRandomCopyBytes(kSecRandomDefault, kCCKeySizeAES128, [key mutableBytes]);

// Setting dictionary for adding to keychain
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:(id)kSecClassKey forKey:(id)kSecClass];
[dict setObject:(id)kSecAttrKeyTypeAES forKey:(id)kSecAttrKeyType];
[dict setObject:kSecAttrKeyClassSymmetric forKey:(id)kSecAttrKeyClass];
[dict setObject:peerTag forKey:(id)kSecAttrApplicationTag];
[dict setObject:[NSNumber numberWithUnsignedInteger:kCCKeySizeAES128] forKey:(id)kSecAttrKeySizeInBits];
[dict setObject:key forKey:(id)kSecValueData];

// Adding to keychain
OSStatus osstatus = SecItemAdd((__bridge CFDictionaryRef)dict, NULL);

//Just give me a result (in this case a label in the app)
[[self statusField] setStringValue:[NSString stringWithFormat:@"Key: %@\nStatus: %@", [key base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength], SecCopyErrorMessageString(osstatus, NULL)]];

What I am doing wrong? Any help would be highly appreciated. Thanks.

Eurobertics
  • 66
  • 1
  • 8

1 Answers1

2

What I am doing wrong? Any help would be highly appreciated.

It looks like kSecAttrKeyClassSymmetric is not supported. From a Google search of Apple source code (SecAttrKeyClassSymmetric site:opensource.apple.com), it looks like you get a NULL from SecKey.c:

case 2: // kSecAttrKeyClassSymmetric
    secwarning("Unsupported symmetric key type: %@", ktype);
    ref = NULL;
    break;
...

Base encode it and use kSecClassGenericPassword. Or, try stuffing it in the keychain without the encoding. An array is an array.

Keep in mind I could be reading those sources wrong. I don't read a lot of Apple source code.

Community
  • 1
  • 1
jww
  • 97,681
  • 90
  • 411
  • 885
  • After digging a lot more in to this, I found out, that you are right. I like Apple, but it seems to turn out, that KeyChain API is not fully supported by the CommonCrypto API. Thanks alot for your advice. To be clear for other who could have the problem: The CC API is a bit incompatible with the KeyChain API for OS X wich is in turn a bit incompatible with the API for iOS. You have to use the Keychain API and if you have a own key (created by CommomCrypto for example) you have to import it with the KeyChain API methods. You can't it store directly. – Eurobertics Mar 18 '14 at 08:28