OS X Keychain: Extracting Private Keys -- possible?
I am attempting to extract the raw bytes of a private key stored in a SecKeyRef
on OS X. How would I go about doing this?
I have read this ~7 year old thread on the Apple CDSA discussion lists, but have found nothing more recent. I am not having the same issue as the original poster in that thread, but it might be on account of me doing the wrong thing. This is what I am currently trying (to no avail):
SecKeyRef keyRef = ...;
CSSM_KEY *cssmKey = NULL;
CSSM_WRAP_KEY wrappedKey = {0};
CSSM_CSP_HANDLE cspHandle = 0;
CSSM_CC_HANDLE ccHandle = 0;
CSSM_ACCESS_CREDENTIALS *creds = NULL;
SecKeyGetCredentials(keyRef, CSSM_ACL_AUTHORIZATION_EXPORT_WRAPPED, kSecCredentialTypeDefault, &creds);
// Tried the following, too.
//CSSM_ACCESS_CREDENTIALS *creds = malloc(sizeof(CSSM_ACCESS_CREDENTIALS));
//memset(creds, 0, sizeof(CSSM_ACCESS_CREDENTIALS));
SecKe开发者_开发技巧yGetCSSMKey(keyRef, &cssmKey);
SecKeyGetCSPHandle(keyRef, &cspHandle);
CSSM_CSP_CreateSymmetricContext(cspHandle,
CSSM_ALGID_NONE,
// Have also tried CSSM_ALGMODE_WRAP
CSSM_ALGMODE_NONE,
creds,
NULL,
NULL,
CSSM_PADDING_NONE,
0,
&ccHandle);
CSSM_WrapKey(ccHandle,
creds,
key,
NULL,
&wrappedKey);
The error code returned by CSSM_WrapKey
is CSSMERR_CSP_INVALID_KEYATTR_MASK
. Any ideas?
I have found the reason I have been having issues: the key I was trying to extract had the CSSM_KEYATTR_SENSITIVE
attributed enabled and I was attempting to perform a "null wrap", i.e. access the unobscured raw bytes.
Lines 285-287 of libsecurity_apple_csp/lib/wrapKey.cpp are as follows:
if(isNullWrap && (keyAttr & CSSM_KEYATTR_SENSITIVE)) {
CssmError::throwMe(CSSMERR_CSP_INVALID_KEYATTR_MASK);
}
If one has to extract a sensitive private key, it must be wrapped -- the default wrapping option for private keys as per the Apple CSP is CSSM_KEYBLOB_WRAPPED_FORMAT_PKCS8
.
精彩评论