objective-c - 从钥匙串(keychain)中检索存储的密码在 XCode 之外失败

标签 objective-c macos osx-mountain-lion

我按照 Apple 在“Keychain Services Programming Guide”中的示例代码将通用密码存储在钥匙串(keychain)中。

只要我在 Xcode 的 Debug模式下运行应用程序,一切正常。但是,当我存档并导出应用程序时,它仍会存储密码(在钥匙串(keychain)访问中可见)但无法检索它们。

钥匙串(keychain)不断返回 errSecAuthFailed (-25293)。这发生在 Mountain Lion 而不是 Snow Leopard。我的应用程序经过代码签名和沙盒处理。对我来说,似乎在检索密码时,钥匙串(keychain)无法将应用程序识别为存储密码的应用程序,因为当我将密码设置为可由任何应用程序访问时,它也能正常工作。

我使用以下代码:

+ (NSString*) retrievePasswordFromKeychainWithKey: (NSString*) theKey {    
    SecKeychainUnlock(NULL, 0, NULL, FALSE);
    const char* userNameUTF8 = [NSUserName() UTF8String];
    uint32_t userNameLength = (uint32_t)strlen(userNameUTF8);
    uint32_t serviceNameLength = (uint32_t)strlen([theKey UTF8String]);

    uint32_t pwLength = 0; 
    void* pwBuffer = nil; 
    SecKeychainItemRef itemRef = nil;
    OSStatus status1 = SecKeychainFindGenericPassword (NULL, serviceNameLength,  serviceNameUTF8, userNameLength, userNameUTF8, &pwLength, &pwBuffer, &itemRef);

    if (status1 == noErr) {
        NSData* pwData = [NSData dataWithBytes:pwBuffer length:pwLength];
        SecKeychainItemFreeContent (NULL,     //No attribute data to release
                                    pwBuffer    //Release data buffer allocated by SecKeychainFindGenericPassword
                                    );
        return [NSString stringWithCString:[pwData bytes] encoding:NSUTF8StringEncoding];
    }
    //status1 is always -25293
    return nil;   
}

最佳答案

好的,我刚刚了解到这是 Mac OS 10.8.0 中的一个 Unresolved 错误。使用 Developer ID 签名的应用无法访问钥匙串(keychain)中的数据。 我希望这将在 10.8.1 中得到修复...

解决方法是不使用您的开发者 ID 对应用进行签名。 (我还读到,在 Lion 下构建的应用程序不受此错误的影响,但我无法对此进行测试)

关于objective-c - 从钥匙串(keychain)中检索存储的密码在 XCode 之外失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11861037/

相关文章:

ios - 找不到纹理图集

python - 属性错误: 'FigureCanvasWxAgg' object has no attribute '_idletimer'

css - 2022 年处理 Safari 和 .webp 图片

macos - USB DriverKit 的 Start 方法中未调用

python - 使用 PyObjC 处理 Mountain Lion 的通知中心

objective-c - 尝试在 Xcode 4.5 中测试运行 iOS 4.3 的 iPad

ios - 滚动时 TableView UILabel 对齐方式发生变化

objective-c - 字符串到 int - cocoa ,objective-c

macos - 回合制游戏的默认玩家人数? (操作系统)

iphone - 保留/复制自动释放的对象