ChaCha20.swift 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. //
  2. // ChaCha20.swift
  3. // CryptoSwift
  4. //
  5. // Created by Marcin Krzyzanowski on 25/08/14.
  6. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. public final class ChaCha20: BlockCipher {
  9. public enum Error: Swift.Error {
  10. case invalidKeyOrInitializationVector
  11. }
  12. public static let blockSize = 64 // 512 / 8
  13. fileprivate let context: Context
  14. fileprivate struct Context {
  15. var input = Array<UInt32>(repeating: 0, count: 16)
  16. init(key: Array<UInt8>, iv: Array<UInt8>) throws {
  17. precondition(iv.count >= 8)
  18. let kbits = key.count * 8
  19. if (kbits != 128 && kbits != 256) {
  20. throw Error.invalidKeyOrInitializationVector
  21. }
  22. // 4 - 8
  23. for i in 0 ..< 4 {
  24. let start = i * 4
  25. input[i + 4] = wordNumber(key[start ..< (start + 4)])
  26. }
  27. var addPos = 0
  28. switch (kbits) {
  29. case 256:
  30. addPos += 16
  31. // sigma
  32. input[0] = 0x61707865 // apxe
  33. input[1] = 0x3320646e // 3 dn
  34. input[2] = 0x79622d32 // yb-2
  35. input[3] = 0x6b206574 // k et
  36. default:
  37. // tau
  38. input[0] = 0x61707865 // apxe
  39. input[1] = 0x3620646e // 6 dn
  40. input[2] = 0x79622d31 // yb-1
  41. input[3] = 0x6b206574 // k et
  42. }
  43. // 8 - 11
  44. for i in 0 ..< 4 {
  45. let start = addPos + (i * 4)
  46. let bytes = key[start ..< (start + 4)]
  47. input[i + 8] = wordNumber(bytes)
  48. }
  49. // iv
  50. input[12] = 0
  51. input[13] = 0
  52. input[14] = wordNumber(iv[0 ..< 4])
  53. input[15] = wordNumber(iv[4 ..< 8])
  54. }
  55. }
  56. public init(key: Array<UInt8>, iv: Array<UInt8>) throws {
  57. self.context = try Context(key: key, iv: iv)
  58. }
  59. fileprivate func wordToByte(_ input: Array<UInt32> /* 64 */ ) -> Array<UInt8>? /* 16 */ {
  60. precondition(input.count == 16)
  61. var x = input
  62. for _ in 0 ..< 10 {
  63. quarterround(&x[0], &x[4], &x[8], &x[12])
  64. quarterround(&x[1], &x[5], &x[9], &x[13])
  65. quarterround(&x[2], &x[6], &x[10], &x[14])
  66. quarterround(&x[3], &x[7], &x[11], &x[15])
  67. quarterround(&x[0], &x[5], &x[10], &x[15])
  68. quarterround(&x[1], &x[6], &x[11], &x[12])
  69. quarterround(&x[2], &x[7], &x[8], &x[13])
  70. quarterround(&x[3], &x[4], &x[9], &x[14])
  71. }
  72. var output = Array<UInt8>()
  73. output.reserveCapacity(16)
  74. for i in 0 ..< 16 {
  75. x[i] = x[i] &+ input[i]
  76. output.append(contentsOf: x[i].bytes().reversed())
  77. }
  78. return output
  79. }
  80. private final func quarterround(_ a: inout UInt32, _ b: inout UInt32, _ c: inout UInt32, _ d: inout UInt32) {
  81. a = a &+ b
  82. d = rotateLeft((d ^ a), by: 16) // FIXME: WAT? n:
  83. c = c &+ d
  84. b = rotateLeft((b ^ c), by: 12)
  85. a = a &+ b
  86. d = rotateLeft((d ^ a), by: 8)
  87. c = c &+ d
  88. b = rotateLeft((b ^ c), by: 7)
  89. }
  90. }
  91. // MARK: Cipher
  92. extension ChaCha20: Cipher {
  93. public func encrypt<C: Collection>(_ bytes: C) throws -> Array<UInt8> where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int {
  94. var ctx = context
  95. var c = Array<UInt8>(repeating: 0, count: bytes.count)
  96. var cPos: Int = 0
  97. var mPos: Int = 0
  98. var bytesCount = bytes.count
  99. while (true) {
  100. if let output = wordToByte(ctx.input) {
  101. ctx.input[12] = ctx.input[12] &+ 1
  102. if (ctx.input[12] == 0) {
  103. ctx.input[13] = ctx.input[13] &+ 1
  104. /* stopping at 2^70 bytes per nonce is user's responsibility */
  105. }
  106. if (bytesCount <= ChaCha20.blockSize) {
  107. for i in 0 ..< bytesCount {
  108. c[i + cPos] = bytes[i + mPos] ^ output[i]
  109. }
  110. return c
  111. }
  112. for i in 0 ..< ChaCha20.blockSize {
  113. c[i + cPos] = bytes[i + mPos] ^ output[i]
  114. }
  115. bytesCount -= ChaCha20.blockSize
  116. cPos += ChaCha20.blockSize
  117. mPos += ChaCha20.blockSize
  118. }
  119. }
  120. }
  121. public func decrypt<C: Collection>(_ bytes: C) throws -> Array<UInt8> where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int {
  122. return try encrypt(bytes)
  123. }
  124. }
  125. // MARK: Encryptor
  126. extension ChaCha20 {
  127. public struct Encryptor: Updatable {
  128. private var accumulated = Array<UInt8>()
  129. private let chacha: ChaCha20
  130. init(chacha: ChaCha20) {
  131. self.chacha = chacha
  132. }
  133. mutating public func update<T: Collection>(withBytes bytes: T, isLast: Bool = false) throws -> Array<UInt8> where T.Iterator.Element == UInt8 {
  134. self.accumulated += bytes
  135. var encrypted = Array<UInt8>()
  136. encrypted.reserveCapacity(self.accumulated.count)
  137. for chunk in BytesSequence(chunkSize: ChaCha20.blockSize, data: self.accumulated) {
  138. if (isLast || self.accumulated.count >= ChaCha20.blockSize) {
  139. encrypted += try chacha.encrypt(chunk)
  140. self.accumulated.removeFirst(chunk.count)
  141. }
  142. }
  143. return encrypted
  144. }
  145. }
  146. }
  147. // MARK: Decryptor
  148. extension ChaCha20 {
  149. public struct Decryptor: Updatable {
  150. private var accumulated = Array<UInt8>()
  151. private var offset: Int = 0
  152. private var offsetToRemove: Int = 0
  153. private let chacha: ChaCha20
  154. init(chacha: ChaCha20) {
  155. self.chacha = chacha
  156. }
  157. mutating public func update<T: Collection>(withBytes bytes: T, isLast: Bool = true) throws -> Array<UInt8> where T.Iterator.Element == UInt8 {
  158. // prepend "offset" number of bytes at the begining
  159. if self.offset > 0 {
  160. self.accumulated += Array<UInt8>(repeating: 0, count: offset) + bytes
  161. self.offsetToRemove = offset
  162. self.offset = 0
  163. } else {
  164. self.accumulated += bytes
  165. }
  166. var plaintext = Array<UInt8>()
  167. plaintext.reserveCapacity(self.accumulated.count)
  168. for chunk in BytesSequence(chunkSize: ChaCha20.blockSize, data: self.accumulated) {
  169. if (isLast || self.accumulated.count >= ChaCha20.blockSize) {
  170. plaintext += try chacha.decrypt(chunk)
  171. // remove "offset" from the beginning of first chunk
  172. if self.offsetToRemove > 0 {
  173. plaintext.removeFirst(self.offsetToRemove)
  174. self.offsetToRemove = 0
  175. }
  176. self.accumulated.removeFirst(chunk.count)
  177. }
  178. }
  179. return plaintext
  180. }
  181. }
  182. }
  183. // MARK: Cryptors
  184. extension ChaCha20: Cryptors {
  185. public func makeEncryptor() -> ChaCha20.Encryptor {
  186. return Encryptor(chacha: self)
  187. }
  188. public func makeDecryptor() -> ChaCha20.Decryptor {
  189. return Decryptor(chacha: self)
  190. }
  191. }
  192. // MARK: Helpers
  193. /// Change array to number. It's here because arrayOfBytes is too slow
  194. private func wordNumber<T: Collection>(_ bytes: T) -> UInt32 where T.Iterator.Element == UInt8, T.IndexDistance == Int {
  195. var value: UInt32 = 0
  196. for i: UInt32 in 0 ..< 4 {
  197. let j = bytes.index(bytes.startIndex, offsetBy: Int(i))
  198. value = value | UInt32(bytes[j]) << (8 * i)
  199. }
  200. return value
  201. }