ChaCha20.swift 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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: ErrorProtocol {
  10. case MissingContext
  11. }
  12. static let blockSize = 64 // 512 / 8
  13. private let stateSize = 16
  14. private var context:Context?
  15. final private class Context {
  16. var input:Array<UInt32> = Array<UInt32>(repeating: 0, count: 16)
  17. deinit {
  18. for i in 0..<input.count {
  19. input[i] = 0x00;
  20. }
  21. }
  22. }
  23. public init?(key:Array<UInt8>, iv:Array<UInt8>) {
  24. if let c = contextSetup(iv: iv, key: key) {
  25. context = c
  26. } else {
  27. return nil
  28. }
  29. }
  30. private final func wordToByte(input:Array<UInt32> /* 64 */) -> Array<UInt8>? /* 16 */ {
  31. if (input.count != stateSize) {
  32. return nil;
  33. }
  34. var x = input
  35. for _ in 0..<10 {
  36. quarterround(a: &x[0], &x[4], &x[8], &x[12])
  37. quarterround(a: &x[1], &x[5], &x[9], &x[13])
  38. quarterround(a: &x[2], &x[6], &x[10], &x[14])
  39. quarterround(a: &x[3], &x[7], &x[11], &x[15])
  40. quarterround(a: &x[0], &x[5], &x[10], &x[15])
  41. quarterround(a: &x[1], &x[6], &x[11], &x[12])
  42. quarterround(a: &x[2], &x[7], &x[8], &x[13])
  43. quarterround(a: &x[3], &x[4], &x[9], &x[14])
  44. }
  45. var output = Array<UInt8>()
  46. output.reserveCapacity(16)
  47. for i in 0..<16 {
  48. x[i] = x[i] &+ input[i]
  49. output.append(contentsOf: x[i].bytes().reversed())
  50. }
  51. return output;
  52. }
  53. private func contextSetup(iv:Array<UInt8>, key:Array<UInt8>) -> Context? {
  54. let ctx = Context()
  55. let kbits = key.count * 8
  56. if (kbits != 128 && kbits != 256) {
  57. return nil
  58. }
  59. // 4 - 8
  60. for i in 0..<4 {
  61. let start = i * 4
  62. ctx.input[i + 4] = wordNumber(bytes: key[start..<(start + 4)])
  63. }
  64. var addPos = 0;
  65. switch (kbits) {
  66. case 256:
  67. addPos += 16
  68. // sigma
  69. ctx.input[0] = 0x61707865 //apxe
  70. ctx.input[1] = 0x3320646e //3 dn
  71. ctx.input[2] = 0x79622d32 //yb-2
  72. ctx.input[3] = 0x6b206574 //k et
  73. default:
  74. // tau
  75. ctx.input[0] = 0x61707865 //apxe
  76. ctx.input[1] = 0x3620646e //6 dn
  77. ctx.input[2] = 0x79622d31 //yb-1
  78. ctx.input[3] = 0x6b206574 //k et
  79. break;
  80. }
  81. // 8 - 11
  82. for i in 0..<4 {
  83. let start = addPos + (i*4)
  84. let bytes = key[start..<(start + 4)]
  85. ctx.input[i + 8] = wordNumber(bytes: bytes)
  86. }
  87. // iv
  88. ctx.input[12] = 0
  89. ctx.input[13] = 0
  90. ctx.input[14] = wordNumber(bytes: iv[0..<4])
  91. ctx.input[15] = wordNumber(bytes: iv[4..<8])
  92. return ctx
  93. }
  94. private final func encryptBytes(message:Array<UInt8>) throws -> Array<UInt8> {
  95. guard let ctx = context else {
  96. throw Error.MissingContext
  97. }
  98. var c:Array<UInt8> = Array<UInt8>(repeating: 0, count: message.count)
  99. var cPos:Int = 0
  100. var mPos:Int = 0
  101. var bytes = message.count
  102. while (true) {
  103. if let output = wordToByte(input: ctx.input) {
  104. ctx.input[12] = ctx.input[12] &+ 1
  105. if (ctx.input[12] == 0) {
  106. ctx.input[13] = ctx.input[13] &+ 1
  107. /* stopping at 2^70 bytes per nonce is user's responsibility */
  108. }
  109. if (bytes <= ChaCha20.blockSize) {
  110. for i in 0..<bytes {
  111. c[i + cPos] = message[i + mPos] ^ output[i]
  112. }
  113. return c
  114. }
  115. for i in 0..<ChaCha20.blockSize {
  116. c[i + cPos] = message[i + mPos] ^ output[i]
  117. }
  118. bytes -= ChaCha20.blockSize
  119. cPos += ChaCha20.blockSize
  120. mPos += ChaCha20.blockSize
  121. }
  122. }
  123. }
  124. private final func quarterround(a:inout UInt32, _ b:inout UInt32, _ c:inout UInt32, _ d:inout UInt32) {
  125. a = a &+ b
  126. d = rotateLeft((d ^ a), by: 16) //FIXME: WAT? n:
  127. c = c &+ d
  128. b = rotateLeft((b ^ c), by: 12);
  129. a = a &+ b
  130. d = rotateLeft((d ^ a), by: 8);
  131. c = c &+ d
  132. b = rotateLeft((b ^ c), by: 7);
  133. }
  134. }
  135. // MARK: Cipher
  136. extension ChaCha20: Cipher {
  137. public func encrypt(bytes:Array<UInt8>) throws -> Array<UInt8> {
  138. guard context != nil else {
  139. throw Error.MissingContext
  140. }
  141. return try encryptBytes(message: bytes)
  142. }
  143. public func decrypt(bytes:Array<UInt8>) throws -> Array<UInt8> {
  144. return try encrypt(bytes: bytes)
  145. }
  146. }
  147. // MARK: Helpers
  148. /// Change array to number. It's here because arrayOfBytes is too slow
  149. private func wordNumber(bytes:ArraySlice<UInt8>) -> UInt32 {
  150. var value:UInt32 = 0
  151. for i:UInt32 in 0..<4 {
  152. let j = bytes.startIndex + Int(i)
  153. value = value | UInt32(bytes[j]) << (8 * i)
  154. }
  155. return value
  156. }