Rabbit.swift 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. //
  2. // Rabbit.swift
  3. // CryptoSwift
  4. //
  5. // Copyright (C) 2014-2017 Krzyżanowski <marcin@krzyzanowskim.com>
  6. // This software is provided 'as-is', without any express or implied warranty.
  7. //
  8. // In no event will the authors be held liable for any damages arising from the use of this software.
  9. //
  10. // 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:
  11. //
  12. // - 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.
  13. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  14. // - This notice may not be removed or altered from any source or binary distribution.
  15. //
  16. private typealias Key = SecureBytes
  17. public final class Rabbit: BlockCipher {
  18. public enum Error: Swift.Error {
  19. case invalidKeyOrInitializationVector
  20. }
  21. /// Size of IV in bytes
  22. public static let ivSize = 64 / 8
  23. /// Size of key in bytes
  24. public static let keySize = 128 / 8
  25. /// Size of block in bytes
  26. public static let blockSize = 128 / 8
  27. /// Key
  28. private let key: Key
  29. /// IV (optional)
  30. private let iv: Array<UInt8>?
  31. /// State variables
  32. private var x = Array<UInt32>(repeating: 0, count: 8)
  33. /// Counter variables
  34. private var c = Array<UInt32>(repeating: 0, count: 8)
  35. /// Counter carry
  36. private var p7: UInt32 = 0
  37. /// 'a' constants
  38. private var a: Array<UInt32> = [
  39. 0x4D34D34D,
  40. 0xD34D34D3,
  41. 0x34D34D34,
  42. 0x4D34D34D,
  43. 0xD34D34D3,
  44. 0x34D34D34,
  45. 0x4D34D34D,
  46. 0xD34D34D3,
  47. ]
  48. // MARK: - Initializers
  49. public convenience init(key: Array<UInt8>) throws {
  50. try self.init(key: key, iv: nil)
  51. }
  52. public init(key: Array<UInt8>, iv: Array<UInt8>?) throws {
  53. self.key = Key(bytes: key)
  54. self.iv = iv
  55. guard key.count == Rabbit.keySize && (iv == nil || iv!.count == Rabbit.ivSize) else {
  56. throw Error.invalidKeyOrInitializationVector
  57. }
  58. }
  59. // MARK: -
  60. fileprivate func setup() {
  61. p7 = 0
  62. // Key divided into 8 subkeys
  63. var k = Array<UInt32>(repeating: 0, count: 8)
  64. for j in 0 ..< 8 {
  65. k[j] = UInt32(key[Rabbit.blockSize - (2 * j + 1)]) | (UInt32(key[Rabbit.blockSize - (2 * j + 2)]) << 8)
  66. }
  67. // Initialize state and counter variables from subkeys
  68. for j in 0 ..< 8 {
  69. if j % 2 == 0 {
  70. x[j] = (k[(j + 1) % 8] << 16) | k[j]
  71. c[j] = (k[(j + 4) % 8] << 16) | k[(j + 5) % 8]
  72. } else {
  73. x[j] = (k[(j + 5) % 8] << 16) | k[(j + 4) % 8]
  74. c[j] = (k[j] << 16) | k[(j + 1) % 8]
  75. }
  76. }
  77. // Iterate system four times
  78. nextState()
  79. nextState()
  80. nextState()
  81. nextState()
  82. // Reinitialize counter variables
  83. for j in 0 ..< 8 {
  84. c[j] = c[j] ^ x[(j + 4) % 8]
  85. }
  86. if let iv = iv {
  87. setupIV(iv)
  88. }
  89. }
  90. private func setupIV(_ iv: Array<UInt8>) {
  91. // 63...56 55...48 47...40 39...32 31...24 23...16 15...8 7...0 IV bits
  92. // 0 1 2 3 4 5 6 7 IV bytes in array
  93. let iv0 = UInt32(bytes: [iv[4], iv[5], iv[6], iv[7]])
  94. let iv1 = UInt32(bytes: [iv[0], iv[1], iv[4], iv[5]])
  95. let iv2 = UInt32(bytes: [iv[0], iv[1], iv[2], iv[3]])
  96. let iv3 = UInt32(bytes: [iv[2], iv[3], iv[6], iv[7]])
  97. // Modify the counter state as function of the IV
  98. c[0] = c[0] ^ iv0
  99. c[1] = c[1] ^ iv1
  100. c[2] = c[2] ^ iv2
  101. c[3] = c[3] ^ iv3
  102. c[4] = c[4] ^ iv0
  103. c[5] = c[5] ^ iv1
  104. c[6] = c[6] ^ iv2
  105. c[7] = c[7] ^ iv3
  106. // Iterate system four times
  107. nextState()
  108. nextState()
  109. nextState()
  110. nextState()
  111. }
  112. private func nextState() {
  113. // Before an iteration the counters are incremented
  114. var carry = p7
  115. for j in 0 ..< 8 {
  116. let prev = c[j]
  117. c[j] = prev &+ a[j] &+ carry
  118. carry = prev > c[j] ? 1 : 0 // detect overflow
  119. }
  120. p7 = carry // save last carry bit
  121. // Iteration of the system
  122. var newX = Array<UInt32>(repeating: 0, count: 8)
  123. newX[0] = g(0) &+ rotateLeft(g(7), by: 16) &+ rotateLeft(g(6), by: 16)
  124. newX[1] = g(1) &+ rotateLeft(g(0), by: 8) &+ g(7)
  125. newX[2] = g(2) &+ rotateLeft(g(1), by: 16) &+ rotateLeft(g(0), by: 16)
  126. newX[3] = g(3) &+ rotateLeft(g(2), by: 8) &+ g(1)
  127. newX[4] = g(4) &+ rotateLeft(g(3), by: 16) &+ rotateLeft(g(2), by: 16)
  128. newX[5] = g(5) &+ rotateLeft(g(4), by: 8) &+ g(3)
  129. newX[6] = g(6) &+ rotateLeft(g(5), by: 16) &+ rotateLeft(g(4), by: 16)
  130. newX[7] = g(7) &+ rotateLeft(g(6), by: 8) &+ g(5)
  131. x = newX
  132. }
  133. private func g(_ j: Int) -> UInt32 {
  134. let sum = x[j] &+ c[j]
  135. let square = UInt64(sum) * UInt64(sum)
  136. return UInt32.init(truncatingIfNeeded: square ^ (square >> 32))
  137. }
  138. fileprivate func nextOutput() -> Array<UInt8> {
  139. nextState()
  140. var output16 = [UInt16](repeating: 0, count: Rabbit.blockSize / 2)
  141. output16[7] = UInt16(truncatingIfNeeded: x[0]) ^ UInt16(truncatingIfNeeded: x[5] >> 16)
  142. output16[6] = UInt16(truncatingIfNeeded: x[0] >> 16) ^ UInt16(truncatingIfNeeded: x[3])
  143. output16[5] = UInt16(truncatingIfNeeded: x[2]) ^ UInt16(truncatingIfNeeded: x[7] >> 16)
  144. output16[4] = UInt16(truncatingIfNeeded: x[2] >> 16) ^ UInt16(truncatingIfNeeded: x[5])
  145. output16[3] = UInt16(truncatingIfNeeded: x[4]) ^ UInt16(truncatingIfNeeded: x[1] >> 16)
  146. output16[2] = UInt16(truncatingIfNeeded: x[4] >> 16) ^ UInt16(truncatingIfNeeded: x[7])
  147. output16[1] = UInt16(truncatingIfNeeded: x[6]) ^ UInt16(truncatingIfNeeded: x[3] >> 16)
  148. output16[0] = UInt16(truncatingIfNeeded: x[6] >> 16) ^ UInt16(truncatingIfNeeded: x[1])
  149. var output8 = Array<UInt8>(repeating: 0, count: Rabbit.blockSize)
  150. for j in 0 ..< output16.count {
  151. output8[j * 2] = UInt8(truncatingIfNeeded: output16[j] >> 8)
  152. output8[j * 2 + 1] = UInt8(truncatingIfNeeded: output16[j])
  153. }
  154. return output8
  155. }
  156. }
  157. // MARK: Cipher
  158. extension Rabbit: Cipher {
  159. public func encrypt<C: Collection>(_ bytes: C) -> Array<UInt8> where C.Element == UInt8, C.IndexDistance == Int, C.Index == Int {
  160. setup()
  161. var result = Array<UInt8>(repeating: 0, count: bytes.count)
  162. var output = nextOutput()
  163. var byteIdx = 0
  164. var outputIdx = 0
  165. while byteIdx < bytes.count {
  166. if (outputIdx == Rabbit.blockSize) {
  167. output = nextOutput()
  168. outputIdx = 0
  169. }
  170. result[byteIdx] = bytes[byteIdx] ^ output[outputIdx]
  171. byteIdx += 1
  172. outputIdx += 1
  173. }
  174. return result
  175. }
  176. public func decrypt<C: Collection>(_ bytes: C) -> Array<UInt8> where C.Element == UInt8, C.IndexDistance == Int, C.Index == Int {
  177. return encrypt(bytes)
  178. }
  179. }