为什么SecItemAdd会给我回复-50(无效参数)

时间:2018-04-03 17:13:27

标签: ios objective-c iphone keychain

我想在钥匙串中存储值“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(无效参数) 我做错了什么?

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

1 个答案:

答案 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