CryptoSwiftMD5.swift 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. //
  2. // CryptoSwiftMD5.Swif
  3. //
  4. // To date, adding CommonCrypto to a Swift framework is problematic. See:
  5. // http://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework
  6. // We're using a subset of CryptoSwift as a (temporary?) alternative.
  7. // The following is an altered source version that only includes MD5. The original software can be found at:
  8. // https://github.com/krzyzanowskim/CryptoSwift
  9. // This is the original copyright notice:
  10. /*
  11. Copyright (C) 2014 Marcin Krzyżanowski <marcin.krzyzanowski@gmail.com>
  12. This software is provided 'as-is', without any express or implied warranty.
  13. In no event will the authors be held liable for any damages arising from the use of this software.
  14. 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:
  15. - 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.
  16. - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  17. - This notice may not be removed or altered from any source or binary distribution.
  18. */
  19. import Foundation
  20. /** array of bytes, little-endian representation */
  21. func arrayOfBytes<T>(value:T, length:Int? = nil) -> [UInt8] {
  22. let totalBytes = length ?? MemoryLayout<T>.size
  23. let valuePointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
  24. valuePointer.pointee = value
  25. let bytesPointer = UnsafeMutablePointer<UInt8>(OpaquePointer(valuePointer))
  26. var bytes = Array<UInt8>(repeating: 0, count: totalBytes)
  27. for j in 0..<min(MemoryLayout<T>.size,totalBytes) {
  28. bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee
  29. }
  30. valuePointer.deinitialize(count: 1)
  31. valuePointer.deallocate()
  32. return bytes
  33. }
  34. extension Int {
  35. /** Array of bytes with optional padding (little-endian) */
  36. public func bytes(totalBytes: Int = MemoryLayout<Int>.size) -> [UInt8] {
  37. return arrayOfBytes(value: self, length: totalBytes)
  38. }
  39. }
  40. extension NSMutableData {
  41. /** Convenient way to append bytes */
  42. internal func appendBytes(arrayOfBytes: [UInt8]) {
  43. self.append(arrayOfBytes, length: arrayOfBytes.count)
  44. }
  45. }
  46. struct BytesSequence: Sequence {
  47. let chunkSize: Int
  48. let data: [UInt8]
  49. func makeIterator() -> AnyIterator<ArraySlice<UInt8>> {
  50. var offset:Int = 0
  51. return AnyIterator {
  52. let end = Swift.min(self.chunkSize, self.data.count - offset)
  53. let result = self.data[offset..<offset + end]
  54. offset += result.count
  55. return !result.isEmpty ? result : nil
  56. }
  57. }
  58. }
  59. class HashBase {
  60. static let size:Int = 16 // 128 / 8
  61. let message: [UInt8]
  62. init (_ message: [UInt8]) {
  63. self.message = message
  64. }
  65. /** Common part for hash calculation. Prepare header data. */
  66. func prepare(_ len:Int) -> [UInt8] {
  67. var tmpMessage = message
  68. // Step 1. Append Padding Bits
  69. tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message
  70. // append "0" bit until message length in bits ≡ 448 (mod 512)
  71. var msgLength = tmpMessage.count
  72. var counter = 0
  73. while msgLength % len != (len - 8) {
  74. counter += 1
  75. msgLength += 1
  76. }
  77. tmpMessage += Array<UInt8>(repeating: 0, count: counter)
  78. return tmpMessage
  79. }
  80. }
  81. func rotateLeft(v: UInt32, n: UInt32) -> UInt32 {
  82. return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n))
  83. }
  84. func sliceToUInt32Array(_ slice: ArraySlice<UInt8>) -> [UInt32] {
  85. var result = [UInt32]()
  86. result.reserveCapacity(16)
  87. for idx in stride(from: slice.startIndex, to: slice.endIndex, by: MemoryLayout<UInt32>.size) {
  88. let val1:UInt32 = (UInt32(slice[idx.advanced(by: 3)]) << 24)
  89. let val2:UInt32 = (UInt32(slice[idx.advanced(by: 2)]) << 16)
  90. let val3:UInt32 = (UInt32(slice[idx.advanced(by: 1)]) << 8)
  91. let val4:UInt32 = UInt32(slice[idx])
  92. let val:UInt32 = val1 | val2 | val3 | val4
  93. result.append(val)
  94. }
  95. return result
  96. }
  97. class MD5 : HashBase {
  98. /** specifies the per-round shift amounts */
  99. private let s: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
  100. 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
  101. 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
  102. 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
  103. /** binary integer part of the sines of integers (Radians) */
  104. private let k: [UInt32] = [0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee,
  105. 0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501,
  106. 0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be,
  107. 0x6b901122,0xfd987193,0xa679438e,0x49b40821,
  108. 0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa,
  109. 0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8,
  110. 0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed,
  111. 0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a,
  112. 0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c,
  113. 0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70,
  114. 0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05,
  115. 0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665,
  116. 0xf4292244,0x432aff97,0xab9423a7,0xfc93a039,
  117. 0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1,
  118. 0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1,
  119. 0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391]
  120. private let h: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
  121. func calculate() -> [UInt8] {
  122. var tmpMessage = prepare(64)
  123. tmpMessage.reserveCapacity(tmpMessage.count + 4)
  124. // initialize hh with hash values
  125. var hh = h
  126. // Step 2. Append Length a 64-bit representation of lengthInBits
  127. let lengthInBits = (message.count * 8)
  128. let lengthBytes = lengthInBits.bytes(totalBytes: 64 / 8)
  129. tmpMessage += lengthBytes.reversed()
  130. // Process the message in successive 512-bit chunks:
  131. let chunkSizeBytes = 512 / 8 // 64
  132. for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
  133. // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
  134. var M = sliceToUInt32Array(chunk)
  135. assert(M.count == 16, "Invalid array")
  136. // Initialize hash value for this chunk:
  137. var A:UInt32 = hh[0]
  138. var B:UInt32 = hh[1]
  139. var C:UInt32 = hh[2]
  140. var D:UInt32 = hh[3]
  141. var dTemp:UInt32 = 0
  142. // Main loop
  143. for j in 0..<k.count {
  144. var g = 0
  145. var F:UInt32 = 0
  146. switch (j) {
  147. case 0...15:
  148. F = (B & C) | ((~B) & D)
  149. g = j
  150. break
  151. case 16...31:
  152. F = (D & B) | (~D & C)
  153. g = (5 * j + 1) % 16
  154. break
  155. case 32...47:
  156. F = B ^ C ^ D
  157. g = (3 * j + 5) % 16
  158. break
  159. case 48...63:
  160. F = C ^ (B | (~D))
  161. g = (7 * j) % 16
  162. break
  163. default:
  164. break
  165. }
  166. dTemp = D
  167. D = C
  168. C = B
  169. B = B &+ rotateLeft(v: A &+ F &+ k[j] &+ M[g], n: s[j])
  170. A = dTemp
  171. }
  172. hh[0] = hh[0] &+ A
  173. hh[1] = hh[1] &+ B
  174. hh[2] = hh[2] &+ C
  175. hh[3] = hh[3] &+ D
  176. }
  177. var result = [UInt8]()
  178. result.reserveCapacity(hh.count / 4)
  179. hh.forEach {
  180. let itemLE = $0.littleEndian
  181. result += [UInt8(itemLE & 0xff), UInt8((itemLE >> 8) & 0xff), UInt8((itemLE >> 16) & 0xff), UInt8((itemLE >> 24) & 0xff)]
  182. }
  183. return result
  184. }
  185. }