MD5.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. //
  2. // MD5.swift
  3. // CryptoSwift
  4. //
  5. // Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
  6. // This software is provided 'as-is', without any express or implied warranty.
  7. //
  8. // In no event will the authors be held liable for any damages arising from the use of this software.
  9. //
  10. // 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:
  11. //
  12. // - 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.
  13. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  14. // - This notice may not be removed or altered from any source or binary distribution.
  15. //
  16. public final class MD5: DigestType {
  17. static let blockSize: Int = 64
  18. static let digestLength: Int = 16 // 128 / 8
  19. fileprivate static let hashInitialValue: Array<UInt32> = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
  20. fileprivate var accumulated = Array<UInt8>()
  21. fileprivate var processedBytesTotalCount: Int = 0
  22. fileprivate var accumulatedHash: Array<UInt32> = MD5.hashInitialValue
  23. /** specifies the per-round shift amounts */
  24. private let s: Array<UInt32> = [
  25. 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
  26. 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
  27. 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
  28. 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
  29. ]
  30. /** binary integer part of the sines of integers (Radians) */
  31. private let k: Array<UInt32> = [
  32. 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
  33. 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
  34. 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
  35. 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
  36. 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
  37. 0xd62f105d, 0x2441453, 0xd8a1e681, 0xe7d3fbc8,
  38. 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
  39. 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
  40. 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
  41. 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
  42. 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05,
  43. 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
  44. 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
  45. 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
  46. 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
  47. 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
  48. ]
  49. public init() {
  50. }
  51. public func calculate(for bytes: Array<UInt8>) -> Array<UInt8> {
  52. do {
  53. return try update(withBytes: bytes.slice, isLast: true)
  54. } catch {
  55. fatalError()
  56. }
  57. }
  58. // mutating currentHash in place is way faster than returning new result
  59. fileprivate func process(block chunk: ArraySlice<UInt8>, currentHash: inout Array<UInt32>) {
  60. assert(chunk.count == 16 * 4)
  61. // Initialize hash value for this chunk:
  62. var A: UInt32 = currentHash[0]
  63. var B: UInt32 = currentHash[1]
  64. var C: UInt32 = currentHash[2]
  65. var D: UInt32 = currentHash[3]
  66. var dTemp: UInt32 = 0
  67. // Main loop
  68. for j in 0..<k.count {
  69. var g = 0
  70. var F: UInt32 = 0
  71. switch j {
  72. case 0...15:
  73. F = (B & C) | ((~B) & D)
  74. g = j
  75. break
  76. case 16...31:
  77. F = (D & B) | (~D & C)
  78. g = (5 * j + 1) % 16
  79. break
  80. case 32...47:
  81. F = B ^ C ^ D
  82. g = (3 * j + 5) % 16
  83. break
  84. case 48...63:
  85. F = C ^ (B | (~D))
  86. g = (7 * j) % 16
  87. break
  88. default:
  89. break
  90. }
  91. dTemp = D
  92. D = C
  93. C = B
  94. // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 and get M[g] value
  95. let gAdvanced = g << 2
  96. var Mg = UInt32(chunk[chunk.startIndex &+ gAdvanced])
  97. Mg |= UInt32(chunk[chunk.startIndex &+ gAdvanced &+ 1]) << 8
  98. Mg |= UInt32(chunk[chunk.startIndex &+ gAdvanced &+ 2]) << 16
  99. Mg |= UInt32(chunk[chunk.startIndex &+ gAdvanced &+ 3]) << 24
  100. B = B &+ rotateLeft(A &+ F &+ k[j] &+ Mg, by: s[j])
  101. A = dTemp
  102. }
  103. currentHash[0] = currentHash[0] &+ A
  104. currentHash[1] = currentHash[1] &+ B
  105. currentHash[2] = currentHash[2] &+ C
  106. currentHash[3] = currentHash[3] &+ D
  107. }
  108. }
  109. extension MD5: Updatable {
  110. public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
  111. accumulated += bytes
  112. if isLast {
  113. let lengthInBits = (processedBytesTotalCount + accumulated.count) * 8
  114. let lengthBytes = lengthInBits.bytes(totalBytes: 64 / 8) // A 64-bit representation of b
  115. // Step 1. Append padding
  116. bitPadding(to: &accumulated, blockSize: MD5.blockSize, allowance: 64 / 8)
  117. // Step 2. Append Length a 64-bit representation of lengthInBits
  118. accumulated += lengthBytes.reversed()
  119. }
  120. var processedBytes = 0
  121. for chunk in accumulated.batched(by: MD5.blockSize) {
  122. if isLast || (accumulated.count - processedBytes) >= MD5.blockSize {
  123. process(block: chunk, currentHash: &accumulatedHash)
  124. processedBytes += chunk.count
  125. }
  126. }
  127. accumulated.removeFirst(processedBytes)
  128. processedBytesTotalCount += processedBytes
  129. // output current hash
  130. var result = Array<UInt8>()
  131. result.reserveCapacity(MD5.digestLength)
  132. for hElement in accumulatedHash {
  133. let hLE = hElement.littleEndian
  134. result += Array<UInt8>(arrayLiteral: UInt8(hLE & 0xff), UInt8((hLE >> 8) & 0xff), UInt8((hLE >> 16) & 0xff), UInt8((hLE >> 24) & 0xff))
  135. }
  136. // reset hash value for instance
  137. if isLast {
  138. accumulatedHash = MD5.hashInitialValue
  139. }
  140. return result
  141. }
  142. }