String+MD5.swift 9.5 KB

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