2 * Find all certs in keychain search list matching specified email address.
4 #include <Security/Security.h>
5 #include <Security/SecKeychainItemPriv.h>
7 #include <security_cdsa_utils/cuPrintCert.h>
10 static void usage(char **argv
)
12 printf("Usage: %s [emailaddrs] [option...]\n", argv
[0]);
14 printf(" -p -- print cert contents\n");
15 printf(" -a -- show all certs, no email match\n");
16 printf(" -A -- add to default keychain\n");
20 int main(int argc
, char **argv
)
26 bool print_cert
= false;
27 bool allCerts
= false;
28 const char *emailAddress
= NULL
;
34 if(argv
[1][0] != '-') {
35 /* normal case, email address specified */
36 emailAddress
= argv
[1];
42 while ((arg
= getopt(argc
, argv
, "aphA")) != -1) {
61 if(!allCerts
&& (emailAddress
== NULL
)) {
62 printf("***You must specify either an email address or the -a option.\n");
67 SecKeychainSearchRef srch
;
68 SecKeychainAttributeList attrList
;
69 SecKeychainAttribute attr
;
70 unsigned numCerts
= 0;
73 attr
.tag
= kSecAlias
; // i.e., email address
74 attr
.length
= strlen(emailAddress
);
75 attr
.data
= (void *)emailAddress
;
77 attrList
.attr
= &attr
;
83 ortn
= SecKeychainSearchCreateFromAttributes(NULL
, // default search list
84 kSecCertificateItemClass
,
88 cssmPerror("SecKeychainSearchCreateFromAttributes", ortn
);
93 SecCertificateRef certRef
= NULL
;
96 ortn
= SecKeychainSearchCopyNext(srch
, (SecKeychainItemRef
*)&certRef
);
100 ortn
= SecCertificateGetData(certRef
, &certData
);
102 cssmPerror("SecCertificateGetData", ortn
);
106 printf("=== Cert %u ===\n", numCerts
);
107 printCertName(certData
.Data
, certData
.Length
, NameBoth
);
109 printCert(certData
.Data
, certData
.Length
, CSSM_FALSE
);
113 * Can't call SecCertificateAddToKeychain directly since this
114 * cert already has a keychain.
116 SecCertificateRef newCertRef
= NULL
;
117 ortn
= SecCertificateCreateFromData(&certData
,
118 CSSM_CERT_X_509v3
, CSSM_CERT_ENCODING_DER
,
121 cssmPerror("SecCertificateCreateFromData", ortn
);
122 printf("***Error adding this cert to default keychain.\n");
125 ortn
= SecCertificateAddToKeychain(newCertRef
, NULL
);
127 cssmPerror("SecCertificateAddToKeychain", ortn
);
128 printf("***Error adding this cert to default keychain.\n");
131 printf("...cert added to default keychain.\n");
133 CFRelease(newCertRef
);
138 } while(ortn
== noErr
);
139 printf("...%u certs found matching email address \'%s\'\n", numCerts
,
140 emailAddress
? emailAddress
: "<any>");