Rabbit.swift 7.0 KB

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