我想在钥匙串中存储值“MyKeyValue”,我喜欢这样:
NSData* key = [@"MyKeyValue" dataUsingEncoding:NSUTF8StringEncoding];
NSData* tag = [@"com.example.MyKey" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* addquery = @{ (id)kSecValueRef: key,
(id)kSecClass: (id)kSecClassKey,
(id)kSecAttrApplicationTag: tag,
};
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)addquery, NULL);
但失败了,错误-50(无效参数) 我做错了什么?
我想在钥匙串中存储一个字符串,如果用户卸载并重新安装我的应用程序,则可以检索该字符串。
答案 0 :(得分:1)
由于kSecValueRef
而导致错误,根据Apple的指南kSecValueRef
接受可以通过SecKeyRef
生成的加密密钥,请在下面找到,
NSData* tag = [@"com.example.keys.mykey" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* attributes =
@{ (id)kSecAttrKeyType: (id)kSecAttrKeyTypeRSA,
(id)kSecAttrKeySizeInBits: @2048,
(id)kSecPrivateKeyAttrs:
@{ (id)kSecAttrIsPermanent: @YES,
(id)kSecAttrApplicationTag: tag,
},
};
CFErrorRef error = NULL;
SecKeyRef privateKey = SecKeyCreateRandomKey((__bridge CFDictionaryRef)attributes,
&error);
SecKeyRef publicKey = SecKeyCopyPublicKey(privateKey);
NSDictionary* addquery = @{ (id)kSecValueRef: (__bridge id)publicKey,
(id)kSecClass: (id)kSecClassKey,
(id)kSecAttrApplicationTag: tag,
};
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)addquery, NULL);
有关详细信息,请参阅Storing Keys in the Keychain