Przeglądaj źródła

Use unmanaged memory buffer in SHA3

Marcin Krzyżanowski 8 lat temu
rodzic
commit
1d01e54ba4

+ 5 - 3
Sources/CryptoSwift/SHA1.swift

@@ -39,6 +39,11 @@ public final class SHA1: DigestType {
         // Extend the sixteen 32-bit words into eighty 32-bit words:
         let M = UnsafeMutablePointer<UInt32>.allocate(capacity: 80)
         M.initialize(to: 0, count: 80)
+        defer {
+            M.deinitialize(count: 80)
+            M.deallocate(capacity: 80)
+        }
+
         for x in 0 ..< 80 {
             switch x {
             case 0 ... 15:
@@ -96,9 +101,6 @@ public final class SHA1: DigestType {
         hh[2] = hh[2] &+ C
         hh[3] = hh[3] &+ D
         hh[4] = hh[4] &+ E
-
-        M.deinitialize(count: 80)
-        M.deallocate(capacity: 80)
     }
 }
 

+ 5 - 4
Sources/CryptoSwift/SHA2.swift

@@ -213,7 +213,11 @@ public final class SHA2: DigestType {
         // Extend the sixteen 32-bit words into sixty-four 32-bit words:
         let M = UnsafeMutablePointer<UInt32>.allocate(capacity: self.k.count)
         M.initialize(to: 0, count: self.k.count)
-
+        defer {
+            M.deinitialize(count: self.k.count)
+            M.deallocate(capacity: self.k.count)
+        }
+        
         for x in 0 ..< self.k.count {
             switch (x) {
             case 0 ... 15:
@@ -264,9 +268,6 @@ public final class SHA2: DigestType {
         hh[5] = hh[5] &+ F
         hh[6] = hh[6] &+ G
         hh[7] = hh[7] &+ H
-
-        M.deinitialize(count: self.k.count)
-        M.deallocate(capacity: self.k.count)
     }
 }
 

+ 12 - 2
Sources/CryptoSwift/SHA3.swift

@@ -105,8 +105,18 @@ public final class SHA3: DigestType {
     ///  3. For all triples (x, y, z) such that 0≤x<5, 0≤y<5, and 0≤z<w, let
     ///     A′[x, y,z] = A[x, y,z] ⊕ D[x,z].
     private func θ(_ a: inout Array<UInt64>) {
-        var c = Array<UInt64>(repeating: 0, count: 5)
-        var d = Array<UInt64>(repeating: 0, count: 5)
+        let c = UnsafeMutablePointer<UInt64>.allocate(capacity: 5)
+        c.initialize(to: 0, count: 5)
+        defer {
+            c.deinitialize(count: 5)
+            c.deallocate(capacity: 5)
+        }
+        let d = UnsafeMutablePointer<UInt64>.allocate(capacity: 5)
+        d.initialize(to: 0, count: 5)
+        defer {
+            d.deinitialize(count: 5)
+            d.deallocate(capacity: 5)
+        }
 
         for i in 0 ..< 5 {
             c[i] = a[i] ^ a[i &+ 5] ^ a[i &+ 10] ^ a[i &+ 15] ^ a[i &+ 20]