String+MD5.swift 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. //
  2. // String+MD5.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 18/09/25.
  6. //
  7. // Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Foundation
  27. import CommonCrypto
  28. extension String: KingfisherCompatibleValue { }
  29. extension KingfisherWrapper where Base == String {
  30. var md5: String {
  31. guard let data = base.data(using: .utf8) else {
  32. return base
  33. }
  34. #if swift(>=5.0)
  35. let message = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
  36. return [UInt8](bytes)
  37. }
  38. #else
  39. let message = data.withUnsafeBytes { bytes in
  40. return [UInt8](UnsafeBufferPointer(start: bytes, count: data.count))
  41. }
  42. #endif
  43. let MD5Calculator = MD5(message)
  44. let MD5Data = MD5Calculator.calculate()
  45. var MD5String = String()
  46. for c in MD5Data {
  47. MD5String += String(format: "%02x", c)
  48. }
  49. return MD5String
  50. }
  51. var ext: String? {
  52. var ext = ""
  53. if let index = base.lastIndex(of: ".") {
  54. let extRange = base.index(index, offsetBy: 1)..<base.endIndex
  55. ext = String(base[extRange])
  56. }
  57. guard let firstSeg = ext.split(separator: "@").first else {
  58. return nil
  59. }
  60. return firstSeg.count > 0 ? String(firstSeg) : nil
  61. }
  62. }
  63. // array of bytes, little-endian representation
  64. func arrayOfBytes<T>(_ value: T, length: Int? = nil) -> [UInt8] {
  65. let totalBytes = length ?? (MemoryLayout<T>.size * 8)
  66. let valuePointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
  67. valuePointer.pointee = value
  68. let bytes = valuePointer.withMemoryRebound(to: UInt8.self, capacity: totalBytes) { (bytesPointer) -> [UInt8] in
  69. var bytes = [UInt8](repeating: 0, count: totalBytes)
  70. for j in 0..<min(MemoryLayout<T>.size, totalBytes) {
  71. bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee
  72. }
  73. return bytes
  74. }
  75. #if swift(>=4.1)
  76. valuePointer.deinitialize(count: 1)
  77. valuePointer.deallocate()
  78. #else
  79. valuePointer.deinitialize()
  80. valuePointer.deallocate(capacity: 1)
  81. #endif
  82. return bytes
  83. }
  84. extension Int {
  85. // Array of bytes with optional padding (little-endian)
  86. func bytes(_ totalBytes: Int = MemoryLayout<Int>.size) -> [UInt8] {
  87. return arrayOfBytes(self, length: totalBytes)
  88. }
  89. }
  90. extension NSMutableData {
  91. // Convenient way to append bytes
  92. func appendBytes(_ arrayOfBytes: [UInt8]) {
  93. append(arrayOfBytes, length: arrayOfBytes.count)
  94. }
  95. }
  96. protocol HashProtocol {
  97. var message: [UInt8] { get }
  98. // Common part for hash calculation. Prepare header data.
  99. func prepare(_ len: Int) -> [UInt8]
  100. }
  101. extension HashProtocol {
  102. func prepare(_ len: Int) -> [UInt8] {
  103. var tmpMessage = message
  104. // Step 1. Append Padding Bits
  105. tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message
  106. // append "0" bit until message length in bits ≡ 448 (mod 512)
  107. var msgLength = tmpMessage.count
  108. var counter = 0
  109. while msgLength % len != (len - 8) {
  110. counter += 1
  111. msgLength += 1
  112. }
  113. tmpMessage += [UInt8](repeating: 0, count: counter)
  114. return tmpMessage
  115. }
  116. }
  117. func toUInt32Array(_ slice: ArraySlice<UInt8>) -> [UInt32] {
  118. var result = [UInt32]()
  119. result.reserveCapacity(16)
  120. for idx in stride(from: slice.startIndex, to: slice.endIndex, by: MemoryLayout<UInt32>.size) {
  121. let d0 = UInt32(slice[idx.advanced(by: 3)]) << 24
  122. let d1 = UInt32(slice[idx.advanced(by: 2)]) << 16
  123. let d2 = UInt32(slice[idx.advanced(by: 1)]) << 8
  124. let d3 = UInt32(slice[idx])
  125. let val: UInt32 = d0 | d1 | d2 | d3
  126. result.append(val)
  127. }
  128. return result
  129. }
  130. struct BytesIterator: IteratorProtocol {
  131. let chunkSize: Int
  132. let data: [UInt8]
  133. init(chunkSize: Int, data: [UInt8]) {
  134. self.chunkSize = chunkSize
  135. self.data = data
  136. }
  137. var offset = 0
  138. mutating func next() -> ArraySlice<UInt8>? {
  139. let end = min(chunkSize, data.count - offset)
  140. let result = data[offset..<offset + end]
  141. offset += result.count
  142. return result.count > 0 ? result : nil
  143. }
  144. }
  145. struct BytesSequence: Sequence {
  146. let chunkSize: Int
  147. let data: [UInt8]
  148. func makeIterator() -> BytesIterator {
  149. return BytesIterator(chunkSize: chunkSize, data: data)
  150. }
  151. }
  152. func rotateLeft(_ value: UInt32, bits: UInt32) -> UInt32 {
  153. return ((value << bits) & 0xFFFFFFFF) | (value >> (32 - bits))
  154. }
  155. class MD5: HashProtocol {
  156. static let size = 16 // 128 / 8
  157. let message: [UInt8]
  158. init (_ message: [UInt8]) {
  159. self.message = message
  160. }
  161. // specifies the per-round shift amounts
  162. private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
  163. 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
  164. 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
  165. 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
  166. // binary integer part of the sines of integers (Radians)
  167. private let sines: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
  168. 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
  169. 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
  170. 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
  171. 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
  172. 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
  173. 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
  174. 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
  175. 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
  176. 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
  177. 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05,
  178. 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
  179. 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
  180. 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
  181. 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
  182. 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391]
  183. private let hashes: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
  184. func calculate() -> [UInt8] {
  185. var tmpMessage = prepare(64)
  186. tmpMessage.reserveCapacity(tmpMessage.count + 4)
  187. // hash values
  188. var hh = hashes
  189. // Step 2. Append Length a 64-bit representation of lengthInBits
  190. let lengthInBits = (message.count * 8)
  191. let lengthBytes = lengthInBits.bytes(64 / 8)
  192. tmpMessage += lengthBytes.reversed()
  193. // Process the message in successive 512-bit chunks:
  194. let chunkSizeBytes = 512 / 8 // 64
  195. for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
  196. // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
  197. let M = toUInt32Array(chunk)
  198. assert(M.count == 16, "Invalid array")
  199. // Initialize hash value for this chunk:
  200. var A: UInt32 = hh[0]
  201. var B: UInt32 = hh[1]
  202. var C: UInt32 = hh[2]
  203. var D: UInt32 = hh[3]
  204. var dTemp: UInt32 = 0
  205. // Main loop
  206. for j in 0 ..< sines.count {
  207. var g = 0
  208. var F: UInt32 = 0
  209. switch j {
  210. case 0...15:
  211. F = (B & C) | ((~B) & D)
  212. g = j
  213. break
  214. case 16...31:
  215. F = (D & B) | (~D & C)
  216. g = (5 * j + 1) % 16
  217. break
  218. case 32...47:
  219. F = B ^ C ^ D
  220. g = (3 * j + 5) % 16
  221. break
  222. case 48...63:
  223. F = C ^ (B | (~D))
  224. g = (7 * j) % 16
  225. break
  226. default:
  227. break
  228. }
  229. dTemp = D
  230. D = C
  231. C = B
  232. B = B &+ rotateLeft((A &+ F &+ sines[j] &+ M[g]), bits: shifts[j])
  233. A = dTemp
  234. }
  235. hh[0] = hh[0] &+ A
  236. hh[1] = hh[1] &+ B
  237. hh[2] = hh[2] &+ C
  238. hh[3] = hh[3] &+ D
  239. }
  240. var result = [UInt8]()
  241. result.reserveCapacity(hh.count / 4)
  242. hh.forEach {
  243. let itemLE = $0.littleEndian
  244. let r1 = UInt8(itemLE & 0xff)
  245. let r2 = UInt8((itemLE >> 8) & 0xff)
  246. let r3 = UInt8((itemLE >> 16) & 0xff)
  247. let r4 = UInt8((itemLE >> 24) & 0xff)
  248. result += [r1, r2, r3, r4]
  249. }
  250. return result
  251. }
  252. }