ChaCha20.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. // https://tools.ietf.org/html/rfc7539
  16. //
  17. public final class ChaCha20: BlockCipher {
  18. public enum Error: Swift.Error {
  19. case invalidKeyOrInitializationVector
  20. case notSupported
  21. }
  22. public static let blockSize = 64 // 512 / 8
  23. public let keySize: Int
  24. fileprivate let key: Key
  25. fileprivate var counter: Array<UInt8>
  26. public init(key: Array<UInt8>, iv nonce: Array<UInt8>) throws {
  27. precondition(nonce.count == 12 || nonce.count == 8)
  28. if key.count != 32 {
  29. throw Error.invalidKeyOrInitializationVector
  30. }
  31. self.key = Key(bytes: key)
  32. self.keySize = self.key.count
  33. if nonce.count == 8 {
  34. self.counter = [0, 0, 0, 0, 0, 0, 0, 0] + nonce
  35. } else {
  36. self.counter = [0, 0, 0, 0] + nonce
  37. }
  38. assert(self.counter.count == 16)
  39. }
  40. /// https://tools.ietf.org/html/rfc7539#section-2.3.
  41. fileprivate func core(block: inout Array<UInt8>, counter: Array<UInt8>, key: Array<UInt8>) {
  42. precondition(block.count == ChaCha20.blockSize)
  43. precondition(counter.count == 16)
  44. precondition(key.count == 32)
  45. let j0: UInt32 = 0x61707865
  46. let j1: UInt32 = 0x3320646e // 0x3620646e sigma/tau
  47. let j2: UInt32 = 0x79622d32
  48. let j3: UInt32 = 0x6b206574
  49. let j4: UInt32 = UInt32(bytes: key[0..<4]).bigEndian
  50. let j5: UInt32 = UInt32(bytes: key[4..<8]).bigEndian
  51. let j6: UInt32 = UInt32(bytes: key[8..<12]).bigEndian
  52. let j7: UInt32 = UInt32(bytes: key[12..<16]).bigEndian
  53. let j8: UInt32 = UInt32(bytes: key[16..<20]).bigEndian
  54. let j9: UInt32 = UInt32(bytes: key[20..<24]).bigEndian
  55. let j10: UInt32 = UInt32(bytes: key[24..<28]).bigEndian
  56. let j11: UInt32 = UInt32(bytes: key[28..<32]).bigEndian
  57. let j12: UInt32 = UInt32(bytes: counter[0..<4]).bigEndian
  58. let j13: UInt32 = UInt32(bytes: counter[4..<8]).bigEndian
  59. let j14: UInt32 = UInt32(bytes: counter[8..<12]).bigEndian
  60. let j15: UInt32 = UInt32(bytes: counter[12..<16]).bigEndian
  61. var (x0, x1, x2, x3, x4, x5, x6, x7) = (j0, j1, j2, j3, j4, j5, j6, j7)
  62. var (x8, x9, x10, x11, x12, x13, x14, x15) = (j8, j9, j10, j11, j12, j13, j14, j15)
  63. for _ in 0..<10 { // 20 rounds
  64. x0 = x0 &+ x4
  65. x12 ^= x0
  66. x12 = (x12 << 16) | (x12 >> 16)
  67. x8 = x8 &+ x12
  68. x4 ^= x8
  69. x4 = (x4 << 12) | (x4 >> 20)
  70. x0 = x0 &+ x4
  71. x12 ^= x0
  72. x12 = (x12 << 8) | (x12 >> 24)
  73. x8 = x8 &+ x12
  74. x4 ^= x8
  75. x4 = (x4 << 7) | (x4 >> 25)
  76. x1 = x1 &+ x5
  77. x13 ^= x1
  78. x13 = (x13 << 16) | (x13 >> 16)
  79. x9 = x9 &+ x13
  80. x5 ^= x9
  81. x5 = (x5 << 12) | (x5 >> 20)
  82. x1 = x1 &+ x5
  83. x13 ^= x1
  84. x13 = (x13 << 8) | (x13 >> 24)
  85. x9 = x9 &+ x13
  86. x5 ^= x9
  87. x5 = (x5 << 7) | (x5 >> 25)
  88. x2 = x2 &+ x6
  89. x14 ^= x2
  90. x14 = (x14 << 16) | (x14 >> 16)
  91. x10 = x10 &+ x14
  92. x6 ^= x10
  93. x6 = (x6 << 12) | (x6 >> 20)
  94. x2 = x2 &+ x6
  95. x14 ^= x2
  96. x14 = (x14 << 8) | (x14 >> 24)
  97. x10 = x10 &+ x14
  98. x6 ^= x10
  99. x6 = (x6 << 7) | (x6 >> 25)
  100. x3 = x3 &+ x7
  101. x15 ^= x3
  102. x15 = (x15 << 16) | (x15 >> 16)
  103. x11 = x11 &+ x15
  104. x7 ^= x11
  105. x7 = (x7 << 12) | (x7 >> 20)
  106. x3 = x3 &+ x7
  107. x15 ^= x3
  108. x15 = (x15 << 8) | (x15 >> 24)
  109. x11 = x11 &+ x15
  110. x7 ^= x11
  111. x7 = (x7 << 7) | (x7 >> 25)
  112. x0 = x0 &+ x5
  113. x15 ^= x0
  114. x15 = (x15 << 16) | (x15 >> 16)
  115. x10 = x10 &+ x15
  116. x5 ^= x10
  117. x5 = (x5 << 12) | (x5 >> 20)
  118. x0 = x0 &+ x5
  119. x15 ^= x0
  120. x15 = (x15 << 8) | (x15 >> 24)
  121. x10 = x10 &+ x15
  122. x5 ^= x10
  123. x5 = (x5 << 7) | (x5 >> 25)
  124. x1 = x1 &+ x6
  125. x12 ^= x1
  126. x12 = (x12 << 16) | (x12 >> 16)
  127. x11 = x11 &+ x12
  128. x6 ^= x11
  129. x6 = (x6 << 12) | (x6 >> 20)
  130. x1 = x1 &+ x6
  131. x12 ^= x1
  132. x12 = (x12 << 8) | (x12 >> 24)
  133. x11 = x11 &+ x12
  134. x6 ^= x11
  135. x6 = (x6 << 7) | (x6 >> 25)
  136. x2 = x2 &+ x7
  137. x13 ^= x2
  138. x13 = (x13 << 16) | (x13 >> 16)
  139. x8 = x8 &+ x13
  140. x7 ^= x8
  141. x7 = (x7 << 12) | (x7 >> 20)
  142. x2 = x2 &+ x7
  143. x13 ^= x2
  144. x13 = (x13 << 8) | (x13 >> 24)
  145. x8 = x8 &+ x13
  146. x7 ^= x8
  147. x7 = (x7 << 7) | (x7 >> 25)
  148. x3 = x3 &+ x4
  149. x14 ^= x3
  150. x14 = (x14 << 16) | (x14 >> 16)
  151. x9 = x9 &+ x14
  152. x4 ^= x9
  153. x4 = (x4 << 12) | (x4 >> 20)
  154. x3 = x3 &+ x4
  155. x14 ^= x3
  156. x14 = (x14 << 8) | (x14 >> 24)
  157. x9 = x9 &+ x14
  158. x4 ^= x9
  159. x4 = (x4 << 7) | (x4 >> 25)
  160. }
  161. x0 = x0 &+ j0
  162. x1 = x1 &+ j1
  163. x2 = x2 &+ j2
  164. x3 = x3 &+ j3
  165. x4 = x4 &+ j4
  166. x5 = x5 &+ j5
  167. x6 = x6 &+ j6
  168. x7 = x7 &+ j7
  169. x8 = x8 &+ j8
  170. x9 = x9 &+ j9
  171. x10 = x10 &+ j10
  172. x11 = x11 &+ j11
  173. x12 = x12 &+ j12
  174. x13 = x13 &+ j13
  175. x14 = x14 &+ j14
  176. x15 = x15 &+ j15
  177. block.replaceSubrange(0..<4, with: x0.bigEndian.bytes())
  178. block.replaceSubrange(4..<8, with: x1.bigEndian.bytes())
  179. block.replaceSubrange(8..<12, with: x2.bigEndian.bytes())
  180. block.replaceSubrange(12..<16, with: x3.bigEndian.bytes())
  181. block.replaceSubrange(16..<20, with: x4.bigEndian.bytes())
  182. block.replaceSubrange(20..<24, with: x5.bigEndian.bytes())
  183. block.replaceSubrange(24..<28, with: x6.bigEndian.bytes())
  184. block.replaceSubrange(28..<32, with: x7.bigEndian.bytes())
  185. block.replaceSubrange(32..<36, with: x8.bigEndian.bytes())
  186. block.replaceSubrange(36..<40, with: x9.bigEndian.bytes())
  187. block.replaceSubrange(40..<44, with: x10.bigEndian.bytes())
  188. block.replaceSubrange(44..<48, with: x11.bigEndian.bytes())
  189. block.replaceSubrange(48..<52, with: x12.bigEndian.bytes())
  190. block.replaceSubrange(52..<56, with: x13.bigEndian.bytes())
  191. block.replaceSubrange(56..<60, with: x14.bigEndian.bytes())
  192. block.replaceSubrange(60..<64, with: x15.bigEndian.bytes())
  193. }
  194. // XORKeyStream
  195. func process(bytes: ArraySlice<UInt8>, counter: inout Array<UInt8>, key: Array<UInt8>) -> Array<UInt8> {
  196. precondition(counter.count == 16)
  197. precondition(key.count == 32)
  198. var block = Array<UInt8>(repeating: 0, count: ChaCha20.blockSize)
  199. var bytesSlice = bytes
  200. var out = Array<UInt8>(reserveCapacity: bytesSlice.count)
  201. while bytesSlice.count >= ChaCha20.blockSize {
  202. self.core(block: &block, counter: counter, key: key)
  203. for (i, x) in block.enumerated() {
  204. out.append(bytesSlice[bytesSlice.startIndex + i] ^ x)
  205. }
  206. var u: UInt32 = 1
  207. for i in 0..<4 {
  208. u += UInt32(counter[i])
  209. counter[i] = UInt8(u & 0xff)
  210. u >>= 8
  211. }
  212. bytesSlice = bytesSlice[bytesSlice.startIndex + ChaCha20.blockSize..<bytesSlice.endIndex]
  213. }
  214. if !bytesSlice.isEmpty {
  215. self.core(block: &block, counter: counter, key: key)
  216. for (i, v) in bytesSlice.enumerated() {
  217. out.append(v ^ block[i])
  218. }
  219. }
  220. return out
  221. }
  222. }
  223. // MARK: Cipher
  224. extension ChaCha20: Cipher {
  225. public func encrypt(_ bytes: ArraySlice<UInt8>) throws -> Array<UInt8> {
  226. self.process(bytes: bytes, counter: &self.counter, key: Array(self.key))
  227. }
  228. public func decrypt(_ bytes: ArraySlice<UInt8>) throws -> Array<UInt8> {
  229. try self.encrypt(bytes)
  230. }
  231. }
  232. // MARK: Encryptor
  233. extension ChaCha20 {
  234. public struct ChaChaEncryptor: Cryptor, Updatable {
  235. private var accumulated = Array<UInt8>()
  236. private let chacha: ChaCha20
  237. init(chacha: ChaCha20) {
  238. self.chacha = chacha
  239. }
  240. public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
  241. self.accumulated += bytes
  242. var encrypted = Array<UInt8>()
  243. encrypted.reserveCapacity(self.accumulated.count)
  244. for chunk in self.accumulated.batched(by: ChaCha20.blockSize) {
  245. if isLast || self.accumulated.count >= ChaCha20.blockSize {
  246. encrypted += try self.chacha.encrypt(chunk)
  247. self.accumulated.removeFirst(chunk.count) // TODO: improve performance
  248. }
  249. }
  250. return encrypted
  251. }
  252. public func seek(to: Int) throws {
  253. throw Error.notSupported
  254. }
  255. }
  256. }
  257. // MARK: Decryptor
  258. extension ChaCha20 {
  259. public struct ChaChaDecryptor: Cryptor, Updatable {
  260. private var accumulated = Array<UInt8>()
  261. private var offset: Int = 0
  262. private var offsetToRemove: Int = 0
  263. private let chacha: ChaCha20
  264. init(chacha: ChaCha20) {
  265. self.chacha = chacha
  266. }
  267. public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = true) throws -> Array<UInt8> {
  268. // prepend "offset" number of bytes at the beginning
  269. if self.offset > 0 {
  270. self.accumulated += Array<UInt8>(repeating: 0, count: self.offset) + bytes
  271. self.offsetToRemove = self.offset
  272. self.offset = 0
  273. } else {
  274. self.accumulated += bytes
  275. }
  276. var plaintext = Array<UInt8>()
  277. plaintext.reserveCapacity(self.accumulated.count)
  278. for chunk in self.accumulated.batched(by: ChaCha20.blockSize) {
  279. if isLast || self.accumulated.count >= ChaCha20.blockSize {
  280. plaintext += try self.chacha.decrypt(chunk)
  281. // remove "offset" from the beginning of first chunk
  282. if self.offsetToRemove > 0 {
  283. plaintext.removeFirst(self.offsetToRemove) // TODO: improve performance
  284. self.offsetToRemove = 0
  285. }
  286. self.accumulated.removeFirst(chunk.count)
  287. }
  288. }
  289. return plaintext
  290. }
  291. public func seek(to: Int) throws {
  292. throw Error.notSupported
  293. }
  294. }
  295. }
  296. // MARK: Cryptors
  297. extension ChaCha20: Cryptors {
  298. //TODO: Use BlockEncryptor/BlockDecryptor
  299. public func makeEncryptor() -> Cryptor & Updatable {
  300. ChaCha20.ChaChaEncryptor(chacha: self)
  301. }
  302. public func makeDecryptor() -> Cryptor & Updatable {
  303. ChaCha20.ChaChaDecryptor(chacha: self)
  304. }
  305. }