Created
July 26, 2019 16:04
-
-
Save dcwatson/27b64c3a3b81730521401df8037a4696 to your computer and use it in GitHub Desktop.
HKDF implementation in Swift using Apple's CryptoKit framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func hkdf_sha256(_ seed: Data, salt: Data, info: Data, outputSize: Int = 32) -> Data? { | |
// It would be nice to make this generic over <H: HashFunction> if HashFunction had byteCount instead of each hash | |
// individually implementing it. | |
let iterations = UInt8(ceil(Double(outputSize) / Double(SHA256.byteCount))) | |
guard iterations <= 255 else { | |
return nil | |
} | |
let prk = HMAC<SHA256>.authenticationCode(for: seed, using: SymmetricKey(data: salt)) | |
let key = SymmetricKey(data: prk) | |
var hkdf = Data() | |
var value = Data() | |
for i in 1...iterations { | |
value.append(info) | |
value.append(i) | |
let code = HMAC<SHA256>.authenticationCode(for: value, using: key) | |
hkdf.append(contentsOf: code) | |
value = Data(code) | |
} | |
return hkdf.prefix(outputSize) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment