Swift:如何从Swift调用CCKeyDerivationPBKDF?

11

我正在尝试从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 beta 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)
    }
2个回答

15

Swift 3:

基于密码的密钥派生可以用于从密码文本推导出加密密钥并保存用于认证目的的密码。

有几种哈希算法可用,包括 SHA1、SHA256、SHA512,这些算法由此示例代码提供。

轮数参数用于使计算变慢,以便攻击者需要在每次尝试中花费大量时间。典型的延迟值介于100毫秒到500毫秒之间,如果性能不可接受,则可以使用较短的值。

此示例需要Common Crypto
必须将桥接标头添加到项目中:
#import <CommonCrypto/CommonCrypto.h>
Security.framework添加到项目中。

参数:

password     password String  
salt         salt Data  
keyByteCount number of key bytes to generate
rounds       Iteration rounds

returns      Derived key


func pbkdf2SHA1(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
    return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA1), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}

func pbkdf2SHA256(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
    return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA256), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}

func pbkdf2SHA512(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
    return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA512), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}

func pbkdf2(hash :CCPBKDFAlgorithm, password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
    let passwordData = password.data(using:String.Encoding.utf8)!
    var derivedKeyData = Data(repeating:0, count:keyByteCount)

    let derivationStatus = derivedKeyData.withUnsafeMutableBytes {derivedKeyBytes in
        salt.withUnsafeBytes { saltBytes in

            CCKeyDerivationPBKDF(
                CCPBKDFAlgorithm(kCCPBKDF2),
                password, passwordData.count,
                saltBytes, salt.count,
                hash,
                UInt32(rounds),
                derivedKeyBytes, derivedKeyData.count)
        }
    }
    if (derivationStatus != 0) {
        print("Error: \(derivationStatus)")
        return nil;
    }

    return derivedKeyData
}

使用示例:

let password     = "password"
//let salt       = "saltData".data(using: String.Encoding.utf8)!
let salt         = Data(bytes: [0x73, 0x61, 0x6c, 0x74, 0x44, 0x61, 0x74, 0x61])
let keyByteCount = 16
let rounds       = 100000

let derivedKey = pbkdf2SHA1(password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
print("derivedKey (SHA1): \(derivedKey! as NSData)")

示例输出:

derivedKey (SHA1): <6b9d4fa3 0385d128 f6d196ee 3f1d6dbf>

Swift 2.x:

测试中参数类型和类改为实例方法的小修改。


func generateAesKeyForPassword(password: String, salt: NSData, roundCount: Int?, error: NSErrorPointer) -> (key: NSData, actualRoundCount: UInt32)?
{
    let nsDerivedKey = NSMutableData(length: kCCKeySizeAES256)
    var actualRoundCount: UInt32

    // Create Swift intermediates for clarity in function calls
    let algorithm: CCPBKDFAlgorithm        = CCPBKDFAlgorithm(kCCPBKDF2)
    let prf:       CCPseudoRandomAlgorithm = CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256)
    let saltBytes  = UnsafePointer<UInt8>(salt.bytes)
    let saltLength = size_t(salt.length)
    let nsPassword        = password as NSString
    let nsPasswordPointer = UnsafePointer<Int8>(nsPassword.cStringUsingEncoding(NSUTF8StringEncoding))
    let nsPasswordLength  = size_t(nsPassword.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
    var nsDerivedKeyPointer = UnsafeMutablePointer<UInt8>(nsDerivedKey.mutableBytes)
    let nsDerivedKeyLength = size_t(nsDerivedKey.length)
    let msec: UInt32 = 300

    if roundCount != nil {
        actualRoundCount = UInt32(roundCount!)
    }
    else {
        actualRoundCount = CCCalibratePBKDF(
            algorithm,
            nsPasswordLength,
            saltLength,
            prf,
            nsDerivedKeyLength,
            msec);
    }

    let result = CCKeyDerivationPBKDF(
        algorithm,
        nsPasswordPointer,   nsPasswordLength,
        saltBytes,           saltLength,
        prf,                 actualRoundCount,
        nsDerivedKeyPointer, nsDerivedKeyLength)

    if result != 0 {
        let errorDescription = "CCKeyDerivationPBKDF failed with error: '\(result)'"
        // error.memory = MyError(domain: ClientErrorType.errorDomain, code: Int(result), descriptionText: errorDescription)
        return nil
    }

    return (nsDerivedKey, actualRoundCount)
}

//额外的好处:

func salt(#length:UInt) -> NSData {
    let salt        = NSMutableData(length: Int(length))
    var saltPointer = UnsafeMutablePointer<UInt8>(salt.mutableBytes)
    SecRandomCopyBytes(kSecRandomDefault, length, saltPointer);
    return salt
}

//测试调用:

let password   = "test pass"
let salt       = self.salt(length:32)
let roundCount = 300
var error: NSError?

let result = self.generateAesKeyForPassword(password, salt:salt, roundCount:roundCount, error:&error)
println("result: \(result)")

输出:

result: Optional((<d279ab8d 8ace67b7 abec844c b9979d20 f2bb0a7f 5af70502 085bf1e4 1016b20c>, 300))

现在在Swift 1.2中,不再需要进行size_t转换。 "C size_t类型系列现在作为Int导入到Swift中,以减少Int和UInt之间的显式类型转换量,并更好地与返回Int的sizeof对齐。" - Xcode 6.3 beta 2发布说明。 - Daniel
如何将行“var nsDerivedKeyPointer = UnsafeMutablePointer<UInt8>(nsDerivedKey.mutableBytes)”更新为Swift 3?谢谢。 - Libor Zapletal
这个答案非常贴切,就像一双手套。 - dede.exe
在Swift 3中,let passwordData = password.data(using:String.Encoding.utf8)!不再是必需的。当您将Swift String传递给类型为UnsafePointer<Int8>!的参数时,编译器会自动为您执行此操作,并确保生成的对象在C函数返回前保持活动状态。也不需要桥接头文件,import CommonCrypto可以正常工作。 - Mecki
@zaph,你能为这个答案添加Swift 5版本吗? - jegadeesh

1

So I believe this works:

let result = CCKeyDerivationPBKDF(CCPBKDFAlgorithm(kCCPBKDF2), NSString(string: 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));

在 Swift 1.2+ 中,不再需要 size_t 转换:

let result = CCKeyDerivationPBKDF(CCPBKDFAlgorithm(kCCPBKDF2), NSString(string: password).UTF8String, passwordLength, UnsafePointer<UInt8>(salt.bytes), salt.length, CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA512), uint(actualRoundCount), UnsafeMutablePointer<UInt8>(derivedKey.mutableBytes), derivedKey.length)

请注意,这是错误的:
NSString(password).UTF8String

应该是这样的:

它本来应该是:

NSString(string: password).UTF8String

编译器错误明显是误导性的(仍处于测试版)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接