SHA3.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. //
  2. // SHA3.swift
  3. // CryptoSwift
  4. //
  5. // Copyright (C) 2014-2017 Krzyżanowski <marcin@krzyzanowskim.com>
  6. // This software is provided 'as-is', without any express or implied warranty.
  7. //
  8. // In no event will the authors be held liable for any damages arising from the use of this software.
  9. //
  10. // 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:
  11. //
  12. // - 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.
  13. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  14. // - This notice may not be removed or altered from any source or binary distribution.
  15. //
  16. // http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf
  17. // http://keccak.noekeon.org/specs_summary.html
  18. //
  19. #if os(Linux) || os(Android) || os(FreeBSD)
  20. import Glibc
  21. #else
  22. import Darwin
  23. #endif
  24. public final class SHA3: DigestType {
  25. let round_constants: Array<UInt64> = [0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000,
  26. 0x000000000000808B, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009,
  27. 0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A,
  28. 0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003,
  29. 0x8000000000008002, 0x8000000000000080, 0x000000000000800A, 0x800000008000000A,
  30. 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008]
  31. public let blockSize: Int
  32. public let digestLength: Int
  33. fileprivate var accumulated = Array<UInt8>()
  34. fileprivate var processedBytesTotalCount: Int = 0
  35. fileprivate var accumulatedHash: Array<UInt64>
  36. public enum Variant: RawRepresentable {
  37. case sha224, sha256, sha384, sha512
  38. var digestLength: Int {
  39. return 100 - (self.blockSize / 2)
  40. }
  41. var blockSize: Int {
  42. return (1600 - self.rawValue * 2) / 8
  43. }
  44. public typealias RawValue = Int
  45. public var rawValue: RawValue {
  46. switch self {
  47. case .sha224:
  48. return 224
  49. case .sha256:
  50. return 256
  51. case .sha384:
  52. return 384
  53. case .sha512:
  54. return 512
  55. }
  56. }
  57. public init?(rawValue: RawValue) {
  58. switch (rawValue) {
  59. case 224:
  60. self = .sha224
  61. break
  62. case 256:
  63. self = .sha256
  64. break
  65. case 384:
  66. self = .sha384
  67. break
  68. case 512:
  69. self = .sha512
  70. break
  71. default:
  72. return nil
  73. }
  74. }
  75. }
  76. public init(variant: SHA3.Variant) {
  77. self.blockSize = variant.blockSize
  78. self.digestLength = variant.digestLength
  79. self.accumulatedHash = Array<UInt64>(repeating: 0, count: self.digestLength)
  80. }
  81. public func calculate(for bytes: Array<UInt8>) -> Array<UInt8> {
  82. do {
  83. return try self.update(withBytes: bytes.slice, isLast: true)
  84. } catch {
  85. return []
  86. }
  87. }
  88. /// 1. For all pairs (x,z) such that 0≤x<5 and 0≤z<w, let
  89. /// C[x,z]=A[x, 0,z] ⊕ A[x, 1,z] ⊕ A[x, 2,z] ⊕ A[x, 3,z] ⊕ A[x, 4,z].
  90. /// 2. For all pairs (x, z) such that 0≤x<5 and 0≤z<w let
  91. /// D[x,z]=C[(x1) mod 5, z] ⊕ C[(x+1) mod 5, (z –1) mod w].
  92. /// 3. For all triples (x, y, z) such that 0≤x<5, 0≤y<5, and 0≤z<w, let
  93. /// A′[x, y,z] = A[x, y,z] ⊕ D[x,z].
  94. private func θ(_ a: inout Array<UInt64>) {
  95. let c = UnsafeMutablePointer<UInt64>.allocate(capacity: 5)
  96. c.initialize(to: 0, count: 5)
  97. defer {
  98. c.deinitialize(count: 5)
  99. c.deallocate(capacity: 5)
  100. }
  101. let d = UnsafeMutablePointer<UInt64>.allocate(capacity: 5)
  102. d.initialize(to: 0, count: 5)
  103. defer {
  104. d.deinitialize(count: 5)
  105. d.deallocate(capacity: 5)
  106. }
  107. for i in 0 ..< 5 {
  108. c[i] = a[i] ^ a[i &+ 5] ^ a[i &+ 10] ^ a[i &+ 15] ^ a[i &+ 20]
  109. }
  110. d[0] = rotateLeft(c[1], by: 1) ^ c[4]
  111. d[1] = rotateLeft(c[2], by: 1) ^ c[0]
  112. d[2] = rotateLeft(c[3], by: 1) ^ c[1]
  113. d[3] = rotateLeft(c[4], by: 1) ^ c[2]
  114. d[4] = rotateLeft(c[0], by: 1) ^ c[3]
  115. for i in 0 ..< 5 {
  116. a[i] ^= d[i]
  117. a[i &+ 5] ^= d[i]
  118. a[i &+ 10] ^= d[i]
  119. a[i &+ 15] ^= d[i]
  120. a[i &+ 20] ^= d[i]
  121. }
  122. }
  123. /// A′[x, y, z]=A[(x &+ 3y) mod 5, x, z]
  124. private func π(_ a: inout Array<UInt64>) {
  125. let a1 = a[1]
  126. a[1] = a[6]
  127. a[6] = a[9]
  128. a[9] = a[22]
  129. a[22] = a[14]
  130. a[14] = a[20]
  131. a[20] = a[2]
  132. a[2] = a[12]
  133. a[12] = a[13]
  134. a[13] = a[19]
  135. a[19] = a[23]
  136. a[23] = a[15]
  137. a[15] = a[4]
  138. a[4] = a[24]
  139. a[24] = a[21]
  140. a[21] = a[8]
  141. a[8] = a[16]
  142. a[16] = a[5]
  143. a[5] = a[3]
  144. a[3] = a[18]
  145. a[18] = a[17]
  146. a[17] = a[11]
  147. a[11] = a[7]
  148. a[7] = a[10]
  149. a[10] = a1
  150. }
  151. /// For all triples (x, y, z) such that 0≤x<5, 0≤y<5, and 0≤z<w, let
  152. /// A′[x, y,z] = A[x, y,z] ⊕ ((A[(x+1) mod 5, y, z] ⊕ 1) ⋅ A[(x+2) mod 5, y, z])
  153. private func χ(_ a: inout Array<UInt64>) {
  154. for i in stride(from: 0, to: 25, by: 5) {
  155. let a0 = a[0 &+ i]
  156. let a1 = a[1 &+ i]
  157. a[0 &+ i] ^= ~a1 & a[2 &+ i]
  158. a[1 &+ i] ^= ~a[2 &+ i] & a[3 &+ i]
  159. a[2 &+ i] ^= ~a[3 &+ i] & a[4 &+ i]
  160. a[3 &+ i] ^= ~a[4 &+ i] & a0
  161. a[4 &+ i] ^= ~a0 & a1
  162. }
  163. }
  164. private func ι(_ a: inout Array<UInt64>, round: Int) {
  165. a[0] ^= round_constants[round]
  166. }
  167. fileprivate func process(block chunk: ArraySlice<UInt64>, currentHash hh: inout Array<UInt64>) {
  168. // expand
  169. hh[0] ^= chunk[0].littleEndian
  170. hh[1] ^= chunk[1].littleEndian
  171. hh[2] ^= chunk[2].littleEndian
  172. hh[3] ^= chunk[3].littleEndian
  173. hh[4] ^= chunk[4].littleEndian
  174. hh[5] ^= chunk[5].littleEndian
  175. hh[6] ^= chunk[6].littleEndian
  176. hh[7] ^= chunk[7].littleEndian
  177. hh[8] ^= chunk[8].littleEndian
  178. if self.blockSize > 72 { // 72 / 8, sha-512
  179. hh[9] ^= chunk[9].littleEndian
  180. hh[10] ^= chunk[10].littleEndian
  181. hh[11] ^= chunk[11].littleEndian
  182. hh[12] ^= chunk[12].littleEndian
  183. if self.blockSize > 104 { // 104 / 8, sha-384
  184. hh[13] ^= chunk[13].littleEndian
  185. hh[14] ^= chunk[14].littleEndian
  186. hh[15] ^= chunk[15].littleEndian
  187. hh[16] ^= chunk[16].littleEndian
  188. if self.blockSize > 136 { // 136 / 8, sha-256
  189. hh[17] ^= chunk[17].littleEndian
  190. // FULL_SHA3_FAMILY_SUPPORT
  191. if self.blockSize > 144 { // 144 / 8, sha-224
  192. hh[18] ^= chunk[18].littleEndian
  193. hh[19] ^= chunk[19].littleEndian
  194. hh[20] ^= chunk[20].littleEndian
  195. hh[21] ^= chunk[21].littleEndian
  196. hh[22] ^= chunk[22].littleEndian
  197. hh[23] ^= chunk[23].littleEndian
  198. hh[24] ^= chunk[24].littleEndian
  199. }
  200. }
  201. }
  202. }
  203. // Keccak-f
  204. for round in 0 ..< 24 {
  205. θ(&hh)
  206. hh[1] = rotateLeft(hh[1], by: 1)
  207. hh[2] = rotateLeft(hh[2], by: 62)
  208. hh[3] = rotateLeft(hh[3], by: 28)
  209. hh[4] = rotateLeft(hh[4], by: 27)
  210. hh[5] = rotateLeft(hh[5], by: 36)
  211. hh[6] = rotateLeft(hh[6], by: 44)
  212. hh[7] = rotateLeft(hh[7], by: 6)
  213. hh[8] = rotateLeft(hh[8], by: 55)
  214. hh[9] = rotateLeft(hh[9], by: 20)
  215. hh[10] = rotateLeft(hh[10], by: 3)
  216. hh[11] = rotateLeft(hh[11], by: 10)
  217. hh[12] = rotateLeft(hh[12], by: 43)
  218. hh[13] = rotateLeft(hh[13], by: 25)
  219. hh[14] = rotateLeft(hh[14], by: 39)
  220. hh[15] = rotateLeft(hh[15], by: 41)
  221. hh[16] = rotateLeft(hh[16], by: 45)
  222. hh[17] = rotateLeft(hh[17], by: 15)
  223. hh[18] = rotateLeft(hh[18], by: 21)
  224. hh[19] = rotateLeft(hh[19], by: 8)
  225. hh[20] = rotateLeft(hh[20], by: 18)
  226. hh[21] = rotateLeft(hh[21], by: 2)
  227. hh[22] = rotateLeft(hh[22], by: 61)
  228. hh[23] = rotateLeft(hh[23], by: 56)
  229. hh[24] = rotateLeft(hh[24], by: 14)
  230. π(&hh)
  231. χ(&hh)
  232. ι(&hh, round: round)
  233. }
  234. }
  235. }
  236. extension SHA3: Updatable {
  237. public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
  238. self.accumulated += bytes
  239. if isLast {
  240. // Add padding
  241. let markByteIndex = self.processedBytesTotalCount &+ self.accumulated.count
  242. if self.accumulated.count == 0 || self.accumulated.count % self.blockSize != 0 {
  243. let r = self.blockSize * 8
  244. let q = (r / 8) - (self.accumulated.count % (r / 8))
  245. self.accumulated += Array<UInt8>(repeating: 0, count: q)
  246. }
  247. self.accumulated[markByteIndex] |= 0x06 // 0x1F for SHAKE
  248. self.accumulated[self.accumulated.count - 1] |= 0x80
  249. }
  250. var processedBytes = 0
  251. for chunk in self.accumulated.batched(by: self.blockSize) {
  252. if (isLast || (self.accumulated.count - processedBytes) >= self.blockSize) {
  253. self.process(block: chunk.toUInt64Array().slice, currentHash: &self.accumulatedHash)
  254. processedBytes += chunk.count
  255. }
  256. }
  257. self.accumulated.removeFirst(processedBytes)
  258. self.processedBytesTotalCount += processedBytes
  259. // TODO: verify performance, reduce vs for..in
  260. let result = self.accumulatedHash.reduce(Array<UInt8>()) { (result, value) -> Array<UInt8> in
  261. return result + value.bigEndian.bytes()
  262. }
  263. // reset hash value for instance
  264. if isLast {
  265. self.accumulatedHash = Array<UInt64>(repeating: 0, count: self.digestLength)
  266. }
  267. return Array(result[0 ..< self.digestLength])
  268. }
  269. }