Parcourir la source

Work on AES performance

Marcin Krzyżanowski il y a 10 ans
Parent
commit
8c4519dbcf

+ 2 - 0
CryptoSwift.xcodeproj/project.pbxproj

@@ -14,6 +14,7 @@
 		751C5C3D19B26B000094C75D /* Poly1305.swift in Sources */ = {isa = PBXBuildFile; fileRef = 751C5C3C19B26B000094C75D /* Poly1305.swift */; };
 		752DEF7719693EA000E17557 /* NSDataExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 752DEF7619693EA000E17557 /* NSDataExtension.swift */; };
 		752E087B199FF27C005B0EA0 /* SHA1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 752E087A199FF27C005B0EA0 /* SHA1.swift */; };
+		753988211AB72E4100FAF3FC /* ArrayExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 754C8FEC19979F94005AD904 /* ArrayExtension.swift */; };
 		75445821196AA2A5002FF20E /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 75445820196AA2A5002FF20E /* Security.framework */; settings = {ATTRIBUTES = (Required, ); }; };
 		7547195119931802002FA5F1 /* IntExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7547195019931802002FA5F1 /* IntExtension.swift */; };
 		754BE45B19693E190098E6F3 /* CryptoSwift.h in Headers */ = {isa = PBXBuildFile; fileRef = 754BE45A19693E190098E6F3 /* CryptoSwift.h */; settings = {ATTRIBUTES = (Public, ); }; };
@@ -434,6 +435,7 @@
 				758A94291A65C67400E46135 /* HMACTests.swift in Sources */,
 				75100F8F19B0BC890005C5F5 /* Poly1305Tests.swift in Sources */,
 				757DA2571A4ED47B002BA3EF /* Helpers.swift in Sources */,
+				753988211AB72E4100FAF3FC /* ArrayExtension.swift in Sources */,
 				754BE46819693E190098E6F3 /* HashTests.swift in Sources */,
 				757DA2591A4ED4D7002BA3EF /* ChaCha20Tests.swift in Sources */,
 				755FB1DA199E347D00475437 /* ExtensionsTest.swift in Sources */,

+ 4 - 1
CryptoSwift.xcodeproj/xcshareddata/xcschemes/CryptoSwift.xcscheme

@@ -40,7 +40,7 @@
       selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
       selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
       shouldUseLaunchSchemeArgsEnv = "YES"
-      buildConfiguration = "Release">
+      buildConfiguration = "Debug">
       <Testables>
          <TestableReference
             skipped = "NO">
@@ -58,6 +58,9 @@
                <Test
                   Identifier = "AESTests/testAESPerformanceCommonCrypto()">
                </Test>
+               <Test
+                  Identifier = "ChaCha20Tests/testChaCha20Performance()">
+               </Test>
                <Test
                   Identifier = "RaufelderTests">
                </Test>

+ 42 - 50
CryptoSwift/AES.swift

@@ -8,31 +8,44 @@
 
 import Foundation
 
-private enum AESVariant:Int {
-    case unknown, aes128, aes192, aes256
-    
-    var Nk:Int { // Nk words
-        return [4,6,8][self.rawValue - 1]
-    }
+public class AES {
     
-    var Nb:Int { // Nb words
-        return 4
+    public enum AESVariant:Int {
+        case unknown, aes128, aes192, aes256
+        
+        var Nk:Int { // Nk words
+            return [4,6,8][self.rawValue - 1]
+        }
+        
+        var Nb:Int { // Nb words
+            return 4
+        }
+        
+        var Nr:Int { // Nr
+            return Nk + 6
+        }
     }
     
-    var Nr:Int { // Nr
-        return Nk + 6
-    }
-}
-
-public class AES {
     public let blockMode:CipherBlockMode
-    static let blockSize:Int = 16 // 128 /8
+    public static let blockSize:Int = 16 // 128 /8
     
-    private let variant:AESVariant
+    public var variant:AESVariant {
+        switch (self.key.count * 8) {
+        case 128:
+            return .aes128
+        case 192:
+            return .aes192
+        case 256:
+            return .aes256
+        default:
+            return .unknown
+        }
+    }
     private let key:[UInt8]
     private let iv:[UInt8]?
+    public lazy var expandedKey:[UInt8] = { AES.expandKey(self.key, variant: self.variant) }()
     
-    private let sBox:[UInt8] = [
+    static private let sBox:[UInt8] = [
         0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 
         0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 
         0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 
@@ -50,7 +63,7 @@ public class AES {
         0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 
         0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16]
     
-    private let invSBox:[UInt8] = [
+    static private let invSBox:[UInt8] = [
         0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3,
         0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f,
         0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54,
@@ -77,7 +90,7 @@ public class AES {
         0x21, 0x0c, 0x7d]
     
     // Parameters for Linear Congruence Generators
-    private let Rcon:[UInt8] = [
+    static private let Rcon:[UInt8] = [
         0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
         0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39,
         0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
@@ -100,21 +113,6 @@ public class AES {
         self.iv = iv
         self.blockMode = blockMode
         
-        switch (key.count * 8) {
-        case 128:
-            self.variant = .aes128
-            break
-        case 192:
-            self.variant = .aes192
-            break
-        case 256:
-            self.variant = .aes256
-            break
-        default:
-            self.variant = .unknown
-            return nil
-        }
-        
         if (blockMode.needIV && iv.count != AES.blockSize) {
             assert(false, "Block size and Initialization Vector must be the same length!")
             return nil
@@ -151,8 +149,6 @@ public class AES {
     }
     
     private func encryptBlock(block:[UInt8]) -> [UInt8]? {
-        let expandedKey = expandKey()
-        
         var state:[[UInt8]] = [[UInt8]](count: variant.Nb, repeatedValue: [UInt8](count: variant.Nb, repeatedValue: 0))
         for (i, row) in enumerate(state) {
             for (j, val) in enumerate(row) {
@@ -163,21 +159,21 @@ public class AES {
         state = addRoundKey(state,expandedKey, 0)
         
         for roundCount in 1..<variant.Nr {
-            state = subBytes(state)
+            subBytes(&state)
             state = shiftRows(state)
             state = mixColumns(state)
             state = addRoundKey(state, expandedKey, roundCount)
         }
         
-        state = subBytes(state)
+        subBytes(&state)
         state = shiftRows(state)
         state = addRoundKey(state, expandedKey, variant.Nr)
-        
-        var out:[UInt8] = [UInt8]()
-        out.reserveCapacity(state.count * state[0].count)
+
+
+        var out = [UInt8](count: state.count * state.first!.count, repeatedValue: 0)
         for i in 0..<state.count {
             for j in 0..<state[i].count {
-                out.append(state[j][i])
+                out[(i * 4) + j] = state[j][i]
             }
         }
         
@@ -208,8 +204,6 @@ public class AES {
     }
     
     private func decryptBlock(block:[UInt8]) -> [UInt8]? {
-        let expandedKey = expandKey()
-        
         var state:[[UInt8]] = [[UInt8]](count: variant.Nb, repeatedValue: [UInt8](count: variant.Nb, repeatedValue: 0))
         for (i, row) in enumerate(state) {
             for (j, val) in enumerate(row) {
@@ -240,7 +234,7 @@ public class AES {
         return out
     }
     
-    public func expandKey() -> [UInt8] {
+    static private func expandKey(key:[UInt8], variant:AESVariant) -> [UInt8] {
         
         /*
         * Function used in the Key Expansion routine that takes a four-byte
@@ -289,21 +283,19 @@ public class AES {
 extension AES {
     
     // byte substitution with table (S-box)
-    public func subBytes(state:[[UInt8]]) -> [[UInt8]] {
-        var result = state
+    public func subBytes(inout state:[[UInt8]]) {
         for (i,row) in enumerate(state) {
             for (j,value) in enumerate(row) {
-                result[i][j] = sBox[Int(value)]
+                state[i][j] = AES.sBox[Int(value)]
             }
         }
-        return result
     }
     
     public func invSubBytes(state:[[UInt8]]) -> [[UInt8]] {
         var result = state
         for (i,row) in enumerate(state) {
             for (j,value) in enumerate(row) {
-                result[i][j] = invSBox[Int(value)]
+                result[i][j] = AES.invSBox[Int(value)]
             }
         }
         return result

+ 4 - 3
CryptoSwift/ArrayExtension.swift

@@ -11,10 +11,11 @@ import Foundation
 extension Array {
     
     /** split in chunks with given chunk size */
-    internal func chunks(chunksize:Int) -> [Array<T>] {
-        var words:[[T]] = [[T]]()
+    func chunks(chunksize:Int) -> [Array<T>] {
+        var words = [[T]]()
+        words.reserveCapacity(self.count / chunksize)        
         for var idx = chunksize; idx <= self.count; idx = idx + chunksize {
-            let word = Array(self[idx - chunksize..<idx])
+            let word = Array(self[idx - chunksize..<idx]) // this is slow for large table
             words.append(word)
         }
         let reminder = Array(suffix(self, self.count % chunksize))

+ 2 - 1
CryptoSwift/CipherBlockMode.swift

@@ -146,7 +146,8 @@ private struct CFBMode: BlockMode {
 private struct ECBMode: BlockMode {
     var needIV:Bool = false
     func encryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) -> [UInt8]? {
-        var out:[UInt8]?
+        var out:[UInt8] = [UInt8]()
+        out.reserveCapacity(blocks.count * blocks[0].count)
         for plaintext in blocks {
             if let encrypted = cipherOperation(block: plaintext) {
                 out = (out ?? [UInt8]()) + encrypted

+ 2 - 1
CryptoSwift/Playground/CryptoPlayground.playground/contents.swift

@@ -1,2 +1,3 @@
 import Foundation
-import CryptoSwift
+
+

+ 6 - 5
CryptoSwiftTests/AESTests.swift

@@ -97,7 +97,8 @@ class AESTests: XCTestCase {
             [0xcd, 0x60, 0xe0, 0xe7],
             [0xba, 0x70, 0xe1, 0x8c]]
         
-        let substituted = AES(key: aesKey, blockMode: .CBC)!.subBytes(input)
+        var substituted = input
+        AES(key: aesKey, blockMode: .CBC)!.subBytes(&substituted)
         XCTAssertTrue(compareMatrix(expected, substituted), "subBytes failed")
         let inverted = AES(key: aesKey, blockMode: .CBC)!.invSubBytes(substituted)
         XCTAssertTrue(compareMatrix(input, inverted), "invSubBytes failed")
@@ -128,7 +129,7 @@ class AESTests: XCTestCase {
         let expected:[UInt8] = [0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0xd6, 0xaa, 0x74, 0xfd, 0xd2, 0xaf, 0x72, 0xfa, 0xda, 0xa6, 0x78, 0xf1, 0xd6, 0xab, 0x76, 0xfe, 0xb6, 0x92, 0xcf, 0xb, 0x64, 0x3d, 0xbd, 0xf1, 0xbe, 0x9b, 0xc5, 0x0, 0x68, 0x30, 0xb3, 0xfe, 0xb6, 0xff, 0x74, 0x4e, 0xd2, 0xc2, 0xc9, 0xbf, 0x6c, 0x59, 0xc, 0xbf, 0x4, 0x69, 0xbf, 0x41, 0x47, 0xf7, 0xf7, 0xbc, 0x95, 0x35, 0x3e, 0x3, 0xf9, 0x6c, 0x32, 0xbc, 0xfd, 0x5, 0x8d, 0xfd, 0x3c, 0xaa, 0xa3, 0xe8, 0xa9, 0x9f, 0x9d, 0xeb, 0x50, 0xf3, 0xaf, 0x57, 0xad, 0xf6, 0x22, 0xaa, 0x5e, 0x39, 0xf, 0x7d, 0xf7, 0xa6, 0x92, 0x96, 0xa7, 0x55, 0x3d, 0xc1, 0xa, 0xa3, 0x1f, 0x6b, 0x14, 0xf9, 0x70, 0x1a, 0xe3, 0x5f, 0xe2, 0x8c, 0x44, 0xa, 0xdf, 0x4d, 0x4e, 0xa9, 0xc0, 0x26, 0x47, 0x43, 0x87, 0x35, 0xa4, 0x1c, 0x65, 0xb9, 0xe0, 0x16, 0xba, 0xf4, 0xae, 0xbf, 0x7a, 0xd2, 0x54, 0x99, 0x32, 0xd1, 0xf0, 0x85, 0x57, 0x68, 0x10, 0x93, 0xed, 0x9c, 0xbe, 0x2c, 0x97, 0x4e, 0x13, 0x11, 0x1d, 0x7f, 0xe3, 0x94, 0x4a, 0x17, 0xf3, 0x7, 0xa7, 0x8b, 0x4d, 0x2b, 0x30, 0xc5]
         
         if let aes = AES(key: aesKey, blockMode: .CBC) {
-            XCTAssertEqual(expected, aes.expandKey(), "expandKey failed")
+            XCTAssertEqual(expected, aes.expandedKey, "expandKey failed")
         } else {
             XCTAssert(false, "")
         }
@@ -146,7 +147,7 @@ class AESTests: XCTestCase {
             [48, 112, 176, 240]]
         
         if let aes = AES(key: aesKey, blockMode: .CBC) {
-            let result = aes.addRoundKey(input, aes.expandKey(), 0)
+            let result = aes.addRoundKey(input, aes.expandedKey, 0)
             XCTAssertTrue(compareMatrix(expected, result), "addRoundKey failed")
         } else {
             XCTAssert(false, "")
@@ -173,14 +174,14 @@ class AESTests: XCTestCase {
             XCTAssert(false, "")
         }
     }
-
+    
     func testAESPerformance() {
         let key:[UInt8] = [0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c];
         let iv:[UInt8] = [0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F]
         let message = [UInt8](count: 1024 * 1024, repeatedValue: 7)
         self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: false, forBlock: { () -> Void in
             self.startMeasuring()
-            let encrypted = AES(key: key, iv: iv, blockMode: .CBC)?.encrypt(message, padding: PKCS7())
+            let encrypted = AES(key: key, iv: iv, blockMode: .ECB)?.encrypt(message, padding: PKCS7())
             self.stopMeasuring()
         })
     }

+ 10 - 0
CryptoSwiftTests/ExtensionsTest.swift

@@ -20,6 +20,16 @@ class ExtensionsTest: XCTestCase {
         super.tearDown()
     }
 
+    func testArrayChunksPerformance() {
+        self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: false, forBlock: { () -> Void in
+            let message = [UInt8](count: 1024 * 1024, repeatedValue: 7)
+            self.startMeasuring()
+            let blocks = message.chunks(AES.blockSize)
+            self.stopMeasuring()
+        })
+    }
+
+    
     func testIntExtension() {
         let i1:Int = 1024
         let i1Array = i1.bytes(32 / 8) // 32 bit