Password Based Key Derivation 2 Swift 3
suggest changePassword Based Key Derivation can be used both for deriving an encryption key from password text and saving a password for authentication purposes.
There are several hash algorithms that can be used including SHA1, SHA256, SHA512 which are provided by this example code.
The rounds parameter makes the calculation slow so that an attacker spends substantial time on each attempt. Typical delays are about 100ms to 500ms. Use fewer rounds only when that cost is unacceptable.
This example requires Common Crypto. Add a bridging header:
#import <CommonCrypto/CommonCrypto.h>
Also add Security.framework to the project. The PRF argument of CCKeyDerivationPBKDF is a CCPseudoRandomAlgorithm. The password pointer is the UTF-8 bytes, not the String value.
Parameters:
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: CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA1), password: password, salt: salt, keyByteCount: keyByteCount, rounds: rounds)
}
func pbkdf2SHA256(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash: CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), password: password, salt: salt, keyByteCount: keyByteCount, rounds: rounds)
}
func pbkdf2SHA512(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash: CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA512), password: password, salt: salt, keyByteCount: keyByteCount, rounds: rounds)
}
func pbkdf2(hash: CCPseudoRandomAlgorithm, 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
passwordData.withUnsafeBytes { (passwordBytes: UnsafePointer<Int8>) in
CCKeyDerivationPBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
passwordBytes, passwordData.count,
saltBytes, salt.count,
hash,
UInt32(rounds),
derivedKeyBytes, keyByteCount)
}
}
}
if (derivationStatus != 0) {
print("Error: \(derivationStatus)")
return nil;
}
return derivedKeyData
}
Example usage:
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)")
Example Output:
derivedKey (SHA1): <6b9d4fa3 0385d128 f6d196ee 3f1d6dbf>
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents