我有一些麻烦,从SecKeyRef导出到CFDataRef包装或存储对称密钥,或简单地用于其他Cocoa代码。
我有以下代码:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
SecKeyRef sessionKey = [self generateRandomSymmetricKey];
CFDataRef sessionKeyData = [self exportSymmetricKeyAsCFData:sessionKey];
}
- (SecKeyRef)generateRandomSymmetricKey {
SecKeyRef cryptoKey = NULL;
CFErrorRef error = NULL;
// Create the dictionary of key parameters
CFMutableDictionaryRef parameters = (__bridge CFMutableDictionaryRef)[NSMutableDictionary dictionaryWithObjectsAndKeys:kSecAttrKeyTypeAES, kSecAttrKeyType, (__bridge CFNumberRef)[NSNumber numberWithInt:256], kSecAttrKeySizeInBits, nil];
// Generate a symmetric key based on the parameters
cryptoKey = SecKeyGenerateSymmetric(parameters, &error);
return cryptoKey;
}
- (CFDataRef)exportSymmetricKeyAsCFData:(SecKeyRef)cryptoKey {
// Create and populate the parameters object with a basic set of values
SecItemImportExportKeyParameters params;
params.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION;
params.flags = 0;
params.passphrase = NULL;
params.alertTitle = NULL;
params.alertPrompt = NULL;
params.accessRef = NULL;
// These two values are for import
params.keyUsage = NULL;
params.keyAttributes = NULL;
// Create and populate the key usage array
CFMutableArrayRef keyUsage = (__bridge CFMutableArrayRef)[NSMutableArray arrayWithObjects:kSecAttrCanEncrypt, kSecAttrCanDecrypt, nil];
// Create and populate the key attributes array
CFMutableArrayRef keyAttributes = (__bridge CFMutableArrayRef)[NSMutableArray array];
// Set the keyUsage and keyAttributes in the params object
params.keyUsage = keyUsage;
params.keyAttributes = keyAttributes;
// Set the external format and flag values appropriately
SecExternalFormat externalFormat = kSecFormatUnknown; // Should result in the default appropriate external format for the given key.
int flags = 0;
// Export the CFData Key
CFDataRef keyData = NULL;
CFShow(cryptoKey);
OSStatus oserr = SecItemExport(cryptoKey, externalFormat, flags, ¶ms, &keyData);
if (oserr) {
fprintf(stderr, "SecItemExport failed (oserr= %d)n", oserr);
exit(-1);
}
NSLog(@"Exported Symmetric Key Data: %@", [(__bridge NSData *)keyData bytes]);
return keyData;
}
但是我的日志里只有:
SecItemExport failed (oserr= -25316)
"oserr= -25316"在SecBase.h中定义为:
errSecDataNotAvailable = -25316,/*无法检索该项的内容。*/
我原本认为这个错误意味着SecKeyRef被提前释放或类似的东西,但正如你从日志中看到的,SecKey报告自己很好。
有什么想法,我错过了什么或做错了吗?谢谢!
与Apple沟通后,发现此问题是由于"Extractable"属性被设置为NO,但无法通过SecKeyGenerateSymmetric()
设置该参数引起的
一个bug已经被归档了,但是在这个bug被解决之前,基本上解决方案是使用折旧法SecKeyGenerate()
。
代替上面的- (SecKeyRef)generateRandomSymmetricKey
方法:
- (SecKeyRef)generateRandomSymmetricKey {
SecKeyRef symmetricKey;
OSStatus oserr = SecKeyGenerate(NULL, CSSM_ALGID_AES, 256, 0, (CSSM_KEYUSE_DECRYPT | CSSM_KEYUSE_ENCRYPT), CSSM_KEYATTR_EXTRACTABLE, NULL, &symmetricKey);
if (oserr) {
NSLog(@"SecKeyGenerate failed: %@", (__bridge NSString *)SecCopyErrorMessageString(oserr, NULL));
exit(-1);
}
return symmetricKey;
}