我在将对称密钥从 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 失败 (osrr= -25316)
“osrr= -25316”在 SecBase.h 中定义为:
errSecDataNotAvailable = -25316, /* 无法检索此项目的内容。*/
我最初认为该错误意味着 SecKeyRef 已提前发布或类似的东西,但正如您从日志中看到的那样,SecKey 报告自己很好。
关于我在这里遗漏或做错了什么的任何想法?谢谢!