I need to store some data of my application in system keychain which should to accessible to all the users in the system. Here is the below sample code :
// Create a SecAccessControlRef for a keychain item with access control
SecAccessControlRef accessControl = SecAccessControlCreateWithFlags(
kCFAllocatorDefault,
kSecAttrAccessibleWhenUnlocked,
kSecAccessControlUserPresence,
NULL
);
// Define a query dictionary for a keychain item
NSDictionary *query = @{
(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrService: @"MyService",
(__bridge id)kSecAttrAccount: @"MyAccount",
(__bridge id)kSecValueData: [@"MyPassword" dataUsingEncoding:NSUTF8StringEncoding],
(__bridge id)kSecAttrAccessControl: (__bridge_transfer id)accessControl,
};
// Add the keychain item to the default keychain (login keychain)
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
if (status != errSecSuccess) {
NSLog(@"Error adding keychain item: %d", (int)status);
}
I tried using SecKeychainOpen to access the system keychain but SecKeychainOpen is deprecated and I could not find any equivalent latest API to support that.
SecKeychainRef systemKeychain;
OSStatus status = SecKeychainOpen("/Library/Keychains/System.keychain", &systemKeychain);
if (status != errSecSuccess) {
NSLog(@"Error opening system keychain: %d", status);
} else {
SecAccessControlRef accessControl = SecAccessControlCreateWithFlags(
kCFAllocatorDefault,
kSecAttrAccessibleWhenUnlocked,
kSecAccessControlUserPresence,
NULL
);
NSDictionary *query = @{
(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrService: @"MyService",
(__bridge id)kSecAttrAccount: @"MyAccount",
(__bridge id)kSecValueData: [@"MyPassword" dataUsingEncoding:NSUTF8StringEncoding],
(__bridge id)kSecUseKeychain: (__bridge id)systemKeychain,
(__bridge id)kSecAttrAccessControl: (__bridge_transfer id)accessControl,
};
// Add the keychain item to the system keychain
status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
if (status != errSecSuccess) {
NSLog(@"Error adding keychain item to system keychain: %d", (int)status);
}
if (systemKeychain) {
CFRelease(systemKeychain);
}
}
ANY suggestions will be helpful, Please help!