Why SecItemAdd return me -50 (invalid params)

浪尽此生 提交于 2019-12-13 04:08:44

问题


I want to store in the keychain the value "MyKeyValue" and I do like this :

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);

but this failed with error -50 (Invalid params) What i did wrong ?

I would like to store in the keychain a string that can be retrieved if the user uninstall and reinstall my app.


回答1:


The error is occurring because of kSecValueRef, as per Apple's guideline kSecValueRef accepts a cryptographic key which can be generated through SecKeyRef, Please find below,

    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);

For more info please refer Storing Keys in the Keychain



来源:https://stackoverflow.com/questions/49635716/why-secitemadd-return-me-50-invalid-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!