String+MD5.swift 9.4 KB

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