我正在尝试编写一些Python来在Mac上的钥匙串中获取证书,以便最终将其放入x509对象中。不幸的是,我编写的代码在调用SecItemCopyMatching API时出现分段错误。我已经尝试了一些方法,但是我什么也没做,因为它只是在说“细分错误”,而不是实际上告诉我哪里出了问题。我想知道是否有人对我的代码有什么误解?
import ctypes
import struct
from ctypes import c_void_p, c_uint16, c_uint32, c_int32, c_char_p, POINTER, byref, Structure
__metaclass__ = type
sec_keychain_ref = sec_keychain_item_ref = c_void_p
cf_mutable_dictionary_ref = c_void_p
OS_status = c_int32
fw = '/System/Library/Frameworks/{name}.framework/Versions/A/{name}'.format
_sec = ctypes.CDLL(fw(name='Security'))
_coref = ctypes.CDLL(fw(name='CoreFoundation'))
SecItemCopyMatching = _sec.SecItemCopyMatching
SecItemCopyMatching.argtypes = (c_void_p, c_void_p)
SecItemCopyMatching.restype = OS_status
CFDictionaryCreateMutable = _coref.CFDictionaryCreateMutable
CFDictionaryCreateMutable.argtypes = (c_void_p, c_int32, c_void_p, c_void_p)
CFDictionaryCreateMutable.restype = cf_mutable_dictionary_ref
CFDictionarySetValue = _coref.CFDictionarySetValue
CFDictionarySetValue.argtypes = (cf_mutable_dictionary_ref, c_void_p, c_void_p)
kCFTypeDictionaryKeyCallBacks = _coref.kCFTypeDictionaryKeyCallBacks
kCFTypeDictionaryValueCallBacks = _coref.kCFTypeDictionaryValueCallBacks
kCFTypeArrayCallBacks = _coref.kCFTypeArrayCallBacks
kSecReturnRef = ctypes.c_void_p.in_dll(_sec, "kSecReturnRef")
kCFBooleanTrue = ctypes.c_void_p.in_dll(_sec, "kCFBooleanTrue")
kSecMatchItemList = ctypes.c_void_p.in_dll(_sec, "kSecMatchItemList")
kSecMatchSearchList = ctypes.c_void_p.in_dll(_sec, "kSecMatchSearchList")
kSecClass = ctypes.c_void_p.in_dll(_sec, "kSecClass")
kSecClassCertificate = ctypes.c_void_p.in_dll(_sec, "kSecClassCertificate")
kSecMatchLimit = ctypes.c_void_p.in_dll(_sec, "kSecMatchLimit")
kSecMatchLimitAll = ctypes.c_void_p.in_dll(_sec, "kSecMatchLimitAll")
CFArrayCreate = _coref.CFArrayCreate
CFArrayCreate.argtypes = (c_void_p, c_void_p, c_int32, c_void_p)
CFArrayCreate.restype = c_void_p
SecKeychainCopyDefault = _sec.SecKeychainCopyDefault
SecKeychainCopyDefault.argtypes = (c_void_p,)
SecKeychainCopyDefault.restype = OS_status
class OpaqueType(Structure):
pass
OpaqueTypeRef = POINTER(OpaqueType)
query = CFDictionaryCreateMutable(None, 0, byref(kCFTypeDictionaryKeyCallBacks), byref(kCFTypeDictionaryValueCallBacks))
constKeyChain = OpaqueTypeRef()
os_status = SecKeychainCopyDefault(byref(constKeyChain))
searchList = CFArrayCreate(None, constKeyChain, 1, byref(kCFTypeArrayCallBacks))
CFDictionarySetValue(query, kSecReturnRef, kCFBooleanTrue)
CFDictionarySetValue(query, kSecMatchLimit, kSecMatchLimitAll)
CFDictionarySetValue(query, kSecClass, kSecClassCertificate)
CFDictionarySetValue(query, kSecMatchSearchList, searchList)
result = OpaqueTypeRef()
os_status = SecItemCopyMatching(query, byref(result))
我敢肯定,用我的一个指针来说这很简单,但是我已经尝试了好几个小时了,而且我什么都没得到。