以编程方式在 OS X 钥匙串中存储对称密钥
Posted
技术标签:
【中文标题】以编程方式在 OS X 钥匙串中存储对称密钥【英文标题】:Storing a symmetric key in OS X keychain programmatically 【发布时间】:2014-02-27 09:56:50 【问题描述】:我有一个对称密钥,我想将它存储在 OS X 钥匙串中。 存储密码和用户名工作正常,所以我改变了我的代码 存储我想稍后由我的应用程序使用的对称密钥。 我使用以下代码作为响应:
指定的属性不存在。
这是我的代码:
// Identifier for symmetric key
static const uint8_t keyIdentfier[] = "net.eurobertics.TestKey";
NSData *tag = [[NSData alloc] initWithBytes:keyIdentfier length:sizeof(keyIdentfier)];
// Simple keygen algo - JUST FOR EXAMPLE DO NOT USE!
NSMutableData *key = [NSMutableData dataWithLength:8];
SecRandomCopyBytes(kSecRandomDefault, 8, key.mutableBytes);
NSString *base64key = [key base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
// Dictionary for keychain - insert a symmetric key with following attributes
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:(id)kSecClassKey forKey:(id)kSecClass];
[dict setObject:tag forKey:(id)kSecAttrApplicationTag];
[dict setObject:[NSNumber numberWithUnsignedInteger:CSSM_ALGID_AES] forKey:(id)kSecAttrKeyType];
[dict setObject:[NSNumber numberWithUnsignedInteger:(unsigned int)(kCCKeySizeAES128 << 3)] forKey:(id)kSecAttrKeySizeInBits];
[dict setObject:[NSNumber numberWithUnsignedInteger:(unsigned int)(kCCKeySizeAES128 << 3)] forKey:(id)kSecAttrEffectiveKeySize];
[dict setObject:(id)kCFBooleanTrue forKey:(id)kSecAttrCanEncrypt];
[dict setObject:(id)kCFBooleanTrue forKey:(id)kSecAttrCanDecrypt];
[dict setObject:(id)kCFBooleanFalse forKey:(id)kSecAttrCanSign];
[dict setObject:(id)kCFBooleanFalse forKey:(id)kSecAttrCanVerify];
[dict setObject:(id)kCFBooleanFalse forKey:(id)kSecAttrCanWrap];
[dict setObject:(id)kCFBooleanFalse forKey:(id)kSecAttrCanUnwrap];
[dict setObject:(id)kCFBooleanFalse forKey:(id)kSecAttrCanDerive];
[dict setObject:key forKey:(id)kSecValueData];
// Insert key into keychain based on dictionary attributes above
OSStatus osstatus = SecItemAdd((__bridge CFDictionaryRef)dict, NULL);
// Set responsefield
[[self responseField] setStringValue:[NSString stringWithFormat:@"Key: %@\n\nStatus: %@", base64key, SecCopyErrorMessageString(osstatus, NULL)]];
我知道 SecItemAdd 主要用于 ios,但我想稍后将我的应用程序移植到 iOS,所以 我想要更兼容。将密钥存储在默认(通常是登录)钥匙串中 对我来说绝对没问题,因为我会定期通过我的应用程序使用密钥。
【问题讨论】:
【参考方案1】:我通过我的另一个问题发现了为什么这不起作用:
Storing a symmetric key in OS X keychain programmatically
希望对某人有所帮助
【讨论】:
以上是关于以编程方式在 OS X 钥匙串中存储对称密钥的主要内容,如果未能解决你的问题,请参考以下文章