String+MD5.swift 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. func kf_MD5() -> String {
  26. if let data = dataUsingEncoding(NSUTF8StringEncoding) {
  27. let MD5Calculator = MD5(data)
  28. let MD5Data = MD5Calculator.calculate()
  29. let resultBytes = UnsafeMutablePointer<CUnsignedChar>(MD5Data.bytes)
  30. let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: MD5Data.length)
  31. return resultEnumerator.reduce(""){ $0 + String(format: "%02x", $1) }
  32. } else {
  33. return self
  34. }
  35. }
  36. }
  37. /** array of bytes, little-endian representation */
  38. func arrayOfBytes<T>(value: T, length: Int? = nil) -> [UInt8] {
  39. let totalBytes = length ?? (sizeofValue(value) * 8)
  40. let valuePointer = UnsafeMutablePointer<T>.alloc(1)
  41. valuePointer.memory = value
  42. let bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer)
  43. var bytes = [UInt8](count: totalBytes, repeatedValue: 0)
  44. for j in 0..<min(sizeof(T), totalBytes) {
  45. bytes[totalBytes - 1 - j] = (bytesPointer + j).memory
  46. }
  47. valuePointer.destroy()
  48. valuePointer.dealloc(1)
  49. return bytes
  50. }
  51. extension Int {
  52. /** Array of bytes with optional padding (little-endian) */
  53. func bytes(totalBytes: Int = sizeof(Int)) -> [UInt8] {
  54. return arrayOfBytes(self, length: totalBytes)
  55. }
  56. }
  57. extension NSMutableData {
  58. /** Convenient way to append bytes */
  59. func appendBytes(arrayOfBytes: [UInt8]) {
  60. appendBytes(arrayOfBytes, length: arrayOfBytes.count)
  61. }
  62. }
  63. class HashBase {
  64. var message: NSData
  65. init(_ message: NSData) {
  66. self.message = message
  67. }
  68. /** Common part for hash calculation. Prepare header data. */
  69. func prepare(len: Int = 64) -> NSMutableData {
  70. let tmpMessage: NSMutableData = NSMutableData(data: self.message)
  71. // Step 1. Append Padding Bits
  72. tmpMessage.appendBytes([0x80]) // append one bit (UInt8 with one bit) to message
  73. // append "0" bit until message length in bits ≡ 448 (mod 512)
  74. var msgLength = tmpMessage.length
  75. var counter = 0
  76. while msgLength % len != (len - 8) {
  77. counter++
  78. msgLength++
  79. }
  80. let bufZeros = UnsafeMutablePointer<UInt8>(calloc(counter, sizeof(UInt8)))
  81. tmpMessage.appendBytes(bufZeros, length: counter)
  82. bufZeros.destroy()
  83. bufZeros.dealloc(1)
  84. return tmpMessage
  85. }
  86. }
  87. func rotateLeft(value: UInt32, bits: UInt32) -> UInt32 {
  88. return ((value << bits) & 0xFFFFFFFF) | (value >> (32 - bits))
  89. }
  90. class MD5: HashBase {
  91. /** specifies the per-round shift amounts */
  92. private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
  93. 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
  94. 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
  95. 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
  96. /** binary integer part of the sines of integers (Radians) */
  97. private let sines: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
  98. 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
  99. 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
  100. 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
  101. 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
  102. 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
  103. 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
  104. 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
  105. 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
  106. 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
  107. 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05,
  108. 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
  109. 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
  110. 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
  111. 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
  112. 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391]
  113. private let hashs: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
  114. func calculate() -> NSData {
  115. let tmpMessage = prepare()
  116. // hash values
  117. var hh = hashs
  118. // Step 2. Append Length a 64-bit representation of lengthInBits
  119. let lengthInBits = (message.length * 8)
  120. let lengthBytes = lengthInBits.bytes(64 / 8)
  121. tmpMessage.appendBytes(Array(lengthBytes.reverse()))
  122. // Process the message in successive 512-bit chunks:
  123. let chunkSizeBytes = 512 / 8 // 64
  124. var leftMessageBytes = tmpMessage.length
  125. for (var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes) {
  126. let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes, leftMessageBytes)))
  127. // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
  128. var M: [UInt32] = [UInt32](count: 16, repeatedValue: 0)
  129. let range = NSRange(location:0, length: M.count * sizeof(UInt32))
  130. chunk.getBytes(UnsafeMutablePointer<Void>(M), range: range)
  131. // Initialize hash value for this chunk:
  132. var A: UInt32 = hh[0]
  133. var B: UInt32 = hh[1]
  134. var C: UInt32 = hh[2]
  135. var D: UInt32 = hh[3]
  136. var dTemp: UInt32 = 0
  137. // Main loop
  138. for j in 0 ..< sines.count {
  139. var g = 0
  140. var F: UInt32 = 0
  141. switch j {
  142. case 0...15:
  143. F = (B & C) | ((~B) & D)
  144. g = j
  145. break
  146. case 16...31:
  147. F = (D & B) | (~D & C)
  148. g = (5 * j + 1) % 16
  149. break
  150. case 32...47:
  151. F = B ^ C ^ D
  152. g = (3 * j + 5) % 16
  153. break
  154. case 48...63:
  155. F = C ^ (B | (~D))
  156. g = (7 * j) % 16
  157. break
  158. default:
  159. break
  160. }
  161. dTemp = D
  162. D = C
  163. C = B
  164. B = B &+ rotateLeft((A &+ F &+ sines[j] &+ M[g]), bits: shifts[j])
  165. A = dTemp
  166. }
  167. hh[0] = hh[0] &+ A
  168. hh[1] = hh[1] &+ B
  169. hh[2] = hh[2] &+ C
  170. hh[3] = hh[3] &+ D
  171. }
  172. let buf: NSMutableData = NSMutableData()
  173. hh.forEach({ (item) -> () in
  174. var i: UInt32 = item.littleEndian
  175. buf.appendBytes(&i, length: sizeofValue(i))
  176. })
  177. return NSData(data: buf)
  178. }
  179. }