How to use “SecItemAdd” to store a symmetric key in OS X?

陌路散爱 提交于 2019-12-20 03:26:14

问题


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.


回答1:


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 (I try to avoid Apple).



来源:https://stackoverflow.com/questions/22172229/how-to-use-secitemadd-to-store-a-symmetric-key-in-os-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!