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