为什么 SecItemAdd return me -50(无效参数)

Why SecItemAdd return me -50 (invalid params)

我想将值 "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(参数无效) 我做错了什么?

我想在钥匙串中存储一个字符串,如果用户卸载并重新安装我的应用程序,可以检索该字符串。

错误的发生是因为 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