OSStatus FetchSEPrivKeyRef()

in macos/macos.c [75:112]


OSStatus FetchSEPrivKeyRef(
    const char* label,
    const char* tag,
    unsigned char* hash,
    SecKeyRef* privKey) {
  CFMutableDictionaryRef query =
      CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, NULL);
  CFDataRef cfTag = StringToDataRef(tag);
  CFStringRef cfLabel = CFStringCreateWithCString(
      kCFAllocatorDefault, label, kCFStringEncodingUTF8);
  CFDictionaryAddValue(query, kSecClass, kSecClassKey);
  CFDictionaryAddValue(query, kSecAttrKeyType, kSecAttrKeyTypeEC);
  CFDictionaryAddValue(query, kSecAttrApplicationTag, cfTag);
  CFDictionaryAddValue(query, kSecAttrLabel, cfLabel);
  CFDictionaryAddValue(query, kSecAttrKeyClass, kSecAttrKeyClassPrivate);
  CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);
  CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);

  if (hash) {
    CFDataRef h = CFDataCreateWithBytesNoCopy(
        kCFAllocatorDefault, (UInt8*)hash, 20, kCFAllocatorNull);
    CFDictionaryAddValue(query, kSecAttrApplicationLabel, h);
  }

  SecKeyRef key = NULL;
  OSStatus status = SecItemCopyMatching(query, (CFTypeRef*)&key);
  CFRelease((CFTypeRef)query);
  CFRelease((CFTypeRef)cfTag);
  CFRelease((CFTypeRef)cfLabel);

  if ((status != errSecSuccess) || (!key))
    return status;

  if (privKey)
    *privKey = key;

  return status;
}