我正在尝试从 Swift 调用 CCKeyDerivationPBKDF。
我已经在我的 Project-Bridging-Header.h 中导入了所需的标头:
#import <CommonCrypto/CommonKeyDerivation.h>
(顺便说一句,在我的项目中导入其他 Objective C 代码时,桥接头似乎可以正常工作)。
在 Xcode 中,我可以从 .swift 文件跳转到此处显示的定义:
int
CCKeyDerivationPBKDF( CCPBKDFAlgorithm algorithm, const char *password, size_t passwordLen,
const uint8_t *salt, size_t saltLen,
CCPseudoRandomAlgorithm prf, uint rounds,
uint8_t *derivedKey, size_t derivedKeyLen)
最后,当我尝试像这样调用函数时:
let result = CCKeyDerivationPBKDF(CCPBKDFAlgorithm(kCCPBKDF2), NSString(password).UTF8String, size_t(passwordLength), UnsafePointer<UInt8>(salt.bytes), size_t(salt.length), CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), uint(actualRoundCount), UnsafeMutablePointer<UInt8>(derivedKey.mutableBytes), size_t(derivedKey.length));
...我得到这个编译器错误:
无法使用类型为“(CCPBKDFAlgorithm,UnsafePointer,size_t,UnsafePointer,size_t,CCPseudoRandomAlgorithm,uint,UnsafeMutablePointer,size_t)”的参数列表调用“init”
我相信所有的转换都是正确的(实际上编译器错误帮助我识别每个参数的每个问题)——这让我认为编译器理解我调用 CCKeyDerivationPBKDF 的意图。
然而,在所有其他转换错误消失之后,编译器感到困惑,并认为我正在尝试使用初始化器构造一个类。
希望有人能告诉我我的方式的错误。
(Xcode 6 测试版 7)
根据要求,上下文中的完整代码:
class func generateAesKeyForPassword(password: String, salt: NSData, roundCount: UInt?, error: NSErrorPointer) -> (key: NSData, actualRoundCount: UInt)?
{
let derivedKey = NSMutableData(length: kCCKeySizeAES256)
let passwordLength = size_t(password.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
var actualRoundCount: UInt
if roundCount != nil
{
actualRoundCount = roundCount!
}
else
{
actualRoundCount = UInt(CCCalibratePBKDF(CCPBKDFAlgorithm(kCCPBKDF2), passwordLength, UInt(salt.length), CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), UInt(derivedKey.length), UInt32(300) /* milliseconds */));
}
let result = CCKeyDerivationPBKDF(CCPBKDFAlgorithm(kCCPBKDF2), NSString(password).UTF8String, size_t(passwordLength), UnsafePointer<UInt8>(salt.bytes), size_t(salt.length), CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), uint(actualRoundCount), UnsafeMutablePointer<UInt8>(derivedKey.mutableBytes), size_t(derivedKey.length));
if result != 0
{
let errorDescription = "CCKeyDerivationPBKDF failed with error: '\(result)'"
error.memory = MyError(domain: ClientErrorType.errorDomain, code: Int(result), descriptionText: errorDescription)
return nil
}
return (NSData(data: derivedKey), actualRoundCount)
}