From 5545badfc578f89dfe0e5b9a6ca389ecfdbb37e2 Mon Sep 17 00:00:00 2001 From: Pointcheval Hugo Date: Sat, 19 Dec 2020 21:45:03 +0100 Subject: [PATCH] Add keyderivation with pbkdf2 in swift --- ios/Classes/KeyDerivation.swift | 40 +++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 ios/Classes/KeyDerivation.swift diff --git a/ios/Classes/KeyDerivation.swift b/ios/Classes/KeyDerivation.swift new file mode 100644 index 0000000..b1a5954 --- /dev/null +++ b/ios/Classes/KeyDerivation.swift @@ -0,0 +1,40 @@ +// +// KeyDerivation.swift +// +// NativeCryptoPlugin +// +// Copyright (c) 2020 +// Author: Hugo Pointcheval +// + +import Foundation +import CommonCrypto + +class KeyDerivation { + func pbkdf2(password: String, salt: String, keyLength: Int, iteration: Int, algorithm: HashAlgorithm) -> Data? { + + let passwordData = password.data(using: .utf8)! + let saltData = salt.data(using: .utf8)! + + var derivedKeyData = Data(repeating: 0, count: keyLength) + var localDerivedKeyData = derivedKeyData + + let derivationStatus = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes in + saltData.withUnsafeBytes { saltBytes in + CCKeyDerivationPBKDF( + CCPBKDFAlgorithm(kCCPBKDF2), + password, passwordData.count, + saltBytes, saltData.count, + algorithm.pbkdf2, + UInt32(iteration), + derivedKeyBytes, localDerivedKeyData.count) + } + } + if (derivationStatus != kCCSuccess) { + print("Error: \(derivationStatus)") + return nil; + } + + return derivedKeyData + } +}