Как написать в System.keychain? - PullRequest
1 голос
/ 22 июля 2010

Я пишу панель настроек, и мне нужно либо обновить, либо сохранить пароль в System.keychain, чтобы другие могли его найти. Вот код, который у меня есть:

Boolean addOrUpdateKey(NSString *service, NSString *key)
{
  OSStatus retVal;
  SecKeychainRef systemKeychainRef;
  SecKeychainItemRef kcItem;
  UInt32 pwSize = 0;
  char *password = NULL;
  AuthorizationRef authRef;
  AuthorizationItem right = { "system.keychain.modify", 0, NULL, 0 };
  AuthorizationRights rightSet = { 1, &right };


  retVal = AuthorizationCreate(&rightSet, kAuthorizationEmptyEnvironment, kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed, &authRef);
  if (retVal != errSecSuccess) {
    NSLog(@"Failed to get right to modify system keychain %@", SecCopyErrorMessageString(retVal, NULL));
    return FALSE;
  }
  SecKeychainSetUserInteractionAllowed(TRUE);
  retVal = SecKeychainOpen("/Library/Keychains/System.keychain", &systemKeychainRef);
  if (retVal != errSecSuccess) {
    NSLog(@"Failed to open System keychain %@", SecCopyErrorMessageString(retVal, NULL));
    return FALSE;
  }
  retVal = SecKeychainUnlock(systemKeychainRef, 0, NULL, FALSE);
  retVal = SecKeychainFindGenericPassword(NULL, 
                                          [service length], 
                                          [service cString], 
                                          0, 
                                          NULL, 
                                          &pwSize, 
                                          (void**)&password, 
                                          &kcItem);
  if (retVal == errSecItemNotFound) {
    retVal = SecKeychainAddGenericPassword(systemKeychainRef, 
                                           [service length], 
                                           [service cString], 
                                           0, 
                                           NULL, 
                                           [key length], 
                                           [key cString], 
                                            &kcItem);
    if (retVal != errSecSuccess) {
      NSLog(@"Failed to add new key to keychain %@", SecCopyErrorMessageString(retVal, NULL));
      return FALSE;
    }
  }

  retVal = SecKeychainItemModifyAttributesAndData(kcItem, NULL, [key length], [key cString]);
  if (retVal != errSecSuccess) {
    NSLog(@"Failed to update password for key %@", SecCopyErrorMessageString(retVal, NULL));
    return FALSE;
  }

  return TRUE;
}

С или без подпрограмм авторизации и того, существует ли ключ, или нет, вызов SecKeychainItemModifyAttributesAndData всегда возвращает -61 (ошибка разрешения записи). Вопрос в том, как мне получить правильные разрешения на запись в системную цепочку для ключей?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...