我想在OS X的钥匙串中存储对称密钥。我在Apple DevDocs上读到我应该使用SecItemAdd
来执行此操作。我也读过CryptoExercise而没有任何解决方案
但是当我这样做时,我总是得到OSStatus
errSecNoSuchAttr (-25303)
。
Codesnippet如下:
//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)]];
我做错了什么?任何帮助将受到高度赞赏。感谢。
答案 0 :(得分:2)
我做错了什么?任何帮助将受到高度赞赏。
看起来不支持kSecAttrKeyClassSymmetric
。通过谷歌搜索Apple源代码(SecAttrKeyClassSymmetric site:opensource.apple.com),看起来你从SecKey.c获得了一个NULL:
case 2: // kSecAttrKeyClassSymmetric
secwarning("Unsupported symmetric key type: %@", ktype);
ref = NULL;
break;
...
对其进行编码并使用kSecClassGenericPassword
。或者,尝试在没有编码的情况下将其填充到钥匙串中。数组是一个数组。
请记住,我可能会错误地阅读这些来源。我没有阅读很多Apple源代码(我试图避开Apple)。