Xcode11 Beta中SecKeyCopyKeyExchangeResult报错:缺少kSecKeyKeyExchangeParameterRequestedSize
Hey there, I've run into this exact issue when transitioning to Xcode 11's SDK, so let's break down what's going wrong and how to fix it.
The core problem here is that Apple tightened the parameter requirements for SecKeyCopyKeyExchangeResult in the SDK included with Xcode 11 (targeting iOS 13+/macOS 10.15+). In older SDKs (like Xcode 10.3), you could get away with passing key-generation attributes instead of proper key-exchange parameters, but the new SDK enforces that you explicitly specify the kSecKeyKeyExchangeParameterRequestedSize parameter.
Looking at your ecdhSecretCalculation function, you're passing keyPairAttr—which is meant for generating key pairs—to the key exchange call. This doesn't include the required requested size parameter, hence the error.
Here's the corrected version of your function:
private func ecdhSecretCalculation(publicKey: SecKey, privateKey: SecKey) -> NSData? { var error: Unmanaged<CFError>? // Use key exchange-specific parameters instead of key-generation attributes let exchangeParams: [String: Any] = [ // Required: Specify the desired shared secret length in bytes // For 256-bit EC keys, this is 32 bytes (256 bits / 8) kSecKeyKeyExchangeParameterRequestedSize as String: 32, // Optional but recommended: Include key type/size info for validation kSecKeyKeyExchangeParameterUserInfo as String: [ kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeySizeInBits as String: 256 ] ] let algorithm: SecKeyAlgorithm = .ecdhKeyExchangeStandardX963SHA256 let sharedSecret = SecKeyCopyKeyExchangeResult( privateKey, algorithm, publicKey, exchangeParams as CFDictionary, &error ) // Add error handling to debug future issues if let error = error?.takeRetainedValue() { print("ECDH secret calculation failed: \(error.localizedDescription)") return nil } return sharedSecret as NSData? }
Key changes explained:
- Added
kSecKeyKeyExchangeParameterRequestedSize: This tells the system exactly how many bytes you want your shared secret to be. For a 256-bit EC key (which you're using), 32 bytes is the correct value. - Replaced key-generation attributes with exchange-specific parameters: The original
keyPairAttrwas designed for creating keys, not performing key exchange. The newexchangeParamsfocuses solely on the parameters needed for ECDH. - Added basic error handling: Instead of force-unwrapping, we now capture and print errors, which will make debugging any future issues much easier.
This should resolve the "kSecKeyKeyExchangeParameterRequestedSize is missing" error and get your ECDH implementation working in Xcode 11 Beta just like it did in Xcode 10.3.
内容的提问来源于stack exchange,提问作者Kaiser Ren

