如何使用"SecItemAdd"在OS X中存储对称密钥? [英] How to use "SecItemAdd" to store a symmetric key in OS X?
问题描述
我想在OS X的钥匙串中存储一个对称密钥.AppleDevDocs读到我应该使用SecItemAdd
来做到这一点.我还阅读了CryptoExercise,但没有针对我的任何解决方案.
但是当我这样做的时候,我总是得到OSStatus
errSecNoSuchAttr (-25303)
.
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 OSStatuserrSecNoSuchAttr (-25303)
.
代码段如下:
//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.
推荐答案
我做错了什么?任何帮助将不胜感激.
What I am doing wrong? Any help would be highly appreciated.
似乎不支持kSecAttrKeyClassSymmetric
.通过Google搜索的Apple源代码( SecAttrKeyClassSymmetric网站:opensource.apple. com ),那么您似乎会从 SecKey.c :
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;
...
对其进行基本编码,然后使用kSecClassGenericPassword
.或者,尝试将其填充到没有编码的钥匙串中.数组就是数组.
Base encode it and use kSecClassGenericPassword
. Or, try stuffing it in the keychain without the encoding. An array is an array.
请记住,我可能错误地阅读了这些资料.我没有读很多Apple源代码(我尽量避免使用Apple).
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).
这篇关于如何使用"SecItemAdd"在OS X中存储对称密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!