ChaCha20.swift 5.8 KB

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