Skip to content

Instantly share code, notes, and snippets.

@acdha
Created March 13, 2009 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acdha/78824 to your computer and use it in GitHub Desktop.
Save acdha/78824 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2.5
import ctypes
Security = ctypes.cdll.LoadLibrary('/System/Library/Frameworks/Security.framework/Versions/Current/Security')
class SecKeychainAttribute(ctypes.Structure):
_fields_ = [('tag', ctypes.c_char_p),
('length', ctypes.c_int32),
('data', ctypes.c_char_p)]
class SecKeychainAttributeList(ctypes.Structure):
_fields_ = [('count', ctypes.c_int),
('attr', SecKeychainAttribute)]
label = "<some label text here>"
plabel = ctypes.c_char_p(label)
tag = 'labl'
attr = SecKeychainAttribute(tag, 1, plabel)
attrList = SecKeychainAttributeList(1, attr)
# http://developer.apple.com/DOCUMENTATION/Security/Reference/keychainservices/Reference/reference.html#//apple_ref/c/tdef/SecItemClass
CSSM_DB_RECORDTYPE_APP_DEFINED_START = 0x80000000
CSSM_DL_DB_RECORD_X509_CERTIFICATE = CSSM_DB_RECORDTYPE_APP_DEFINED_START + 0x1000
kSecCertificateItemClass = CSSM_DL_DB_RECORD_X509_CERTIFICATE
# Keychain Manager error codes from MacErrors.h
MacErrors = {
0: "No Error",
-25291: "errKCNotAvailable",
-25292: "errKCReadOnly",
-25293: "errKCAuthFailed",
-25294: "errKCNoSuchKeychain",
-25295: "errKCInvalidKeychain",
-25296: "errKCDuplicateKeychain",
-25297: "errKCDuplicateCallback",
-25298: "errKCInvalidCallback",
-25299: "errKCDuplicateItem",
-25300: "errKCItemNotFound",
-25301: "errKCBufferTooSmall",
-25302: "errKCDataTooLarge",
-25303: "errKCNoSuchAttr",
-25304: "errKCInvalidItemRef",
-25305: "errKCInvalidSearchRef",
-25306: "errKCNoSuchClass",
-25307: "errKCNoDefaultKeychain",
-25308: "errKCInteractionNotAllowed",
-25309: "errKCReadOnlyAttr",
-25310: "errKCWrongKCVersion",
-25311: "errKCKeySizeNotAllowed",
-25312: "errKCNoStorageModule",
-25313: "errKCNoCertificateModule",
-25314: "errKCNoPolicyModule",
-25315: "errKCInteractionRequired",
-25316: "errKCDataNotAvailable",
-25317: "errKCDataNotModifiable",
-25318: "errKCCreateChainFailed",
}
searchRef = ctypes.c_void_p()
itemRef = ctypes.c_void_p()
rc = Security.SecKeychainSearchCreateFromAttributes(
None,
kSecCertificateItemClass,
ctypes.byref(attrList),
ctypes.pointer(searchRef)
)
print "SecKeychainSearchCreateFromAttributes returned %d: %s" % (rc, MacErrors[rc])
status = Security.SecKeychainSearchCopyNext (
searchRef,
ctypes.byref(itemRef)
)
print "SecKeychainSearchCopyNext returned %d: %s" % (rc, MacErrors[rc])
if searchRef:
CFRelease(searchRef)
status = Security.SecKeychainItemDelete(
itemRef
)
print "SecKeychainItemDelete returned %d: %s" % (rc, MacErrors[rc])
if itemRef:
CFRelease(itemRef)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment