PBKDF2.swift 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. //
  2. // CryptoSwift
  3. //
  4. // Copyright (C) 2014-2021 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
  5. // This software is provided 'as-is', without any express or implied warranty.
  6. //
  7. // In no event will the authors be held liable for any damages arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
  10. //
  11. // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
  12. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  13. // - This notice may not be removed or altered from any source or binary distribution.
  14. //
  15. // https://www.ietf.org/rfc/rfc2898.txt
  16. //
  17. #if canImport(Darwin)
  18. import Darwin
  19. #elseif canImport(Glibc)
  20. import Glibc
  21. #elseif canImport(ucrt)
  22. import ucrt
  23. #endif
  24. public extension PKCS5 {
  25. /// A key derivation function.
  26. ///
  27. /// PBKDF2 - Password-Based Key Derivation Function 2. Key stretching technique.
  28. /// DK = PBKDF2(PRF, Password, Salt, c, dkLen)
  29. struct PBKDF2 {
  30. public enum Error: Swift.Error {
  31. case invalidInput
  32. case derivedKeyTooLong
  33. }
  34. private let salt: Array<UInt8> // S
  35. fileprivate let iterations: Int // c
  36. private let numBlocks: Int // l
  37. private let dkLen: Int
  38. fileprivate let prf: HMAC
  39. /// - parameters:
  40. /// - salt: salt
  41. /// - variant: hash variant
  42. /// - iterations: iteration count, a positive integer
  43. /// - keyLength: intended length of derived key
  44. /// - variant: MAC variant. Defaults to SHA256
  45. public init(password: Array<UInt8>, salt: Array<UInt8>, iterations: Int = 4096 /* c */, keyLength: Int? = nil /* dkLen */, variant: HMAC.Variant = .sha2(.sha256)) throws {
  46. precondition(iterations > 0)
  47. let prf = HMAC(key: password, variant: variant)
  48. guard iterations > 0 && !salt.isEmpty else {
  49. throw Error.invalidInput
  50. }
  51. self.dkLen = keyLength ?? variant.digestLength
  52. let keyLengthFinal = Double(dkLen)
  53. let hLen = Double(prf.variant.digestLength)
  54. if keyLengthFinal > (pow(2, 32) - 1) * hLen {
  55. throw Error.derivedKeyTooLong
  56. }
  57. self.salt = salt
  58. self.iterations = iterations
  59. self.prf = prf
  60. self.numBlocks = Int(ceil(Double(keyLengthFinal) / hLen)) // l = ceil(keyLength / hLen)
  61. }
  62. public func calculate() throws -> Array<UInt8> {
  63. var ret = Array<UInt8>()
  64. ret.reserveCapacity(self.numBlocks * self.prf.variant.digestLength)
  65. for i in 1...self.numBlocks {
  66. // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter
  67. if let value = try calculateBlock(self.salt, blockNum: i) {
  68. ret.append(contentsOf: value)
  69. }
  70. }
  71. return Array(ret.prefix(self.dkLen))
  72. }
  73. }
  74. }
  75. private extension PKCS5.PBKDF2 {
  76. func ARR(_ i: Int) -> Array<UInt8> {
  77. var inti = Array<UInt8>(repeating: 0, count: 4)
  78. inti[0] = UInt8((i >> 24) & 0xff)
  79. inti[1] = UInt8((i >> 16) & 0xff)
  80. inti[2] = UInt8((i >> 8) & 0xff)
  81. inti[3] = UInt8(i & 0xff)
  82. return inti
  83. }
  84. // F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c
  85. // U_1 = PRF (P, S || INT (i))
  86. func calculateBlock(_ salt: Array<UInt8>, blockNum: Int) throws -> Array<UInt8>? {
  87. guard let u1 = try? prf.authenticate(salt + ARR(blockNum)) else { // blockNum.bytes() is slower
  88. return nil
  89. }
  90. var u = u1
  91. var ret = u
  92. if iterations > 1 {
  93. // U_2 = PRF (P, U_1) ,
  94. // U_c = PRF (P, U_{c-1}) .
  95. for _ in 2...iterations {
  96. u = try prf.authenticate(u)
  97. for x in 0..<ret.count {
  98. ret[x] = ret[x] ^ u[x]
  99. }
  100. }
  101. }
  102. return ret
  103. }
  104. }