简体   繁体   中英

Objective C - SecItemAdd has error:EXC_BAD_ACCESS (first time) and errSecDuplicateItem (second time)

I use this code http://wiki.effectiveprogramming.com/index.php?title=CocoaEncryption&redirect=no in my application to implement Login function. But I have a error method saveRSAPublicKey:

+ (BOOL)saveRSAPublicKey:(NSData*)publicKey appTag:(NSString*)appTag overwrite:(BOOL)overwrite {
    //Error here (when first call) - Program received signal: "EXC_BAD_ACCESS" -> crash
    OSStatus status = SecItemAdd((CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:
                                                   (id)kSecClassKey, kSecClass,
                                                   (id)kSecAttrKeyTypeRSA, kSecAttrKeyType,
                                                   (id)kSecAttrKeyClassPublic, kSecAttrKeyClass,
                                                   kCFBooleanTrue, kSecAttrIsPermanent,
                                                   [appTag dataUsingEncoding:NSUTF8StringEncoding], kSecAttrApplicationTag,
                                                   publicKey, kSecValueData,
                                                   kCFBooleanTrue, kSecReturnPersistentRef,
                                                   nil],
                                                   NULL);   //don't need public key ref

    DebugLog(@"result = %@", [KeychainUtil fetchStatus:status]);

    if(status == noErr)
        return YES;
    else if(status == errSecDuplicateItem && overwrite == YES)
        return [CryptoUtil updateRSAPublicKey:publicKey appTag:appTag];

    return NO;
}

When I call saveRSAPublickey for first time, I can't create OSStatus and my application is crashed. When I call saveRSAPublickey for second time: status == errSecDuplicateItem and run [CryptoUtil updateRSAPublicKey:publicKey appTag:appTag] -> success.

It's difficult to find this problem when debugging because it just only appear in new device ( have never been installed my app). Finally, I have found the error by the way: set new appTag before call saveRSAPublicKey. I see in system.log:

Apr 6 12:30:29 MACs-MacBook-Pro securityd[4372]: unable to access hwaes key

Please help me.!! Thanks all.

If you pass NULL for the 2nd arg (where your result would come out), then you're not allowed to have a Return Type Key set when calling SecItemAdd() (change kCFBooleanTrue, kSecReturnPersistentRef to kCFBooleanFalse, kSecReturnPersistentRef or just delete it).

I submitted a bug report on this just now.

I would guess that publicKey or, more likely, appTag don't contain what you think they do. Try logging them out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM