String+MD5.swift 9.6 KB

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