String+MD5.swift 9.8 KB

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