Parcourir la source

Fix CCM Decryption. Add tests.

Marcin Krzyzanowski il y a 6 ans
Parent
commit
9f09989420

+ 7 - 8
Sources/CryptoSwift/BlockMode/CCM.swift

@@ -47,7 +47,7 @@ public struct CCM: StreamMode {
         self.nonce = nonce
         self.tagLength = tagLength
         self.additionalAuthenticatedData = additionalAuthenticatedData
-        self.messageLength = messageLength - tagLength
+        self.messageLength = messageLength // - tagLength
     }
 
     // decrypt
@@ -89,7 +89,7 @@ class CCMModeWorker: StreamModeWorker, SeekableModeWorker, CounterModeWorker, Fi
     }
 
     init(blockSize: Int, nonce: ArraySlice<UInt8>, messageLength: Int,  additionalAuthenticatedData: [UInt8]?, expectedTag: Array<UInt8>? = nil, tagLength: Int, cipherOperation: @escaping CipherOperationOnBlock) {
-        self.blockSize = 16// blockSize
+        self.blockSize = 16 // CCM is defined for 128 block size
         self.tagLength = tagLength
         self.additionalBufferSize = tagLength
         self.messageLength = messageLength
@@ -165,8 +165,8 @@ class CCMModeWorker: StreamModeWorker, SeekableModeWorker, CounterModeWorker, Fi
         // concatenate T at the end
         guard let S0 = try? S(i: 0) else { return ciphertext }
 
-        let tag = xor(last_y.prefix(tagLength), S0) as ArraySlice<UInt8>
-        return ciphertext + tag
+        let computedTag = xor(last_y.prefix(tagLength), S0) as ArraySlice<UInt8>
+        return ciphertext + computedTag
     }
 
     func decrypt(block ciphertext: ArraySlice<UInt8>) -> Array<UInt8> {
@@ -199,9 +199,7 @@ class CCMModeWorker: StreamModeWorker, SeekableModeWorker, CounterModeWorker, Fi
 
     func finalize(decrypt plaintext: ArraySlice<UInt8>) throws -> ArraySlice<UInt8> {
         // concatenate T at the end
-        guard let S0 = try? S(i: 0) else { return plaintext }
-
-        let computedTag = xor(last_y.prefix(tagLength), S0) as Array<UInt8>
+        let computedTag = Array(last_y.prefix(tagLength))
         guard let expectedTag = self.expectedTag, expectedTag == computedTag else {
             throw CCM.Error.fail
         }
@@ -213,7 +211,8 @@ class CCMModeWorker: StreamModeWorker, SeekableModeWorker, CounterModeWorker, Fi
         // get tag of additionalBufferSize size
         // `ciphertext` contains at least additionalBufferSize bytes
         // overwrite expectedTag property used later for verification
-        self.expectedTag = Array(ciphertext.suffix(tagLength))
+        guard let S0 = try? S(i: 0) else { return ciphertext }
+        self.expectedTag = xor(ciphertext.suffix(tagLength), S0) as [UInt8]
         return ciphertext[ciphertext.startIndex..<ciphertext.endIndex.advanced(by: -Swift.min(tagLength,ciphertext.count))]
     }
 

+ 18 - 6
Sources/CryptoSwift/StreamDecryptor.swift

@@ -16,6 +16,7 @@ final class StreamDecryptor: Cryptor, Updatable {
     private let blockSize: Int
     private var worker: CipherModeWorker
     private let padding: Padding
+    private var accumulated = Array<UInt8>()
 
     private var lastBlockRemainder = 0
 
@@ -29,18 +30,27 @@ final class StreamDecryptor: Cryptor, Updatable {
     public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool) throws -> Array<UInt8> {
         // TODO: accumulate `worker.additionalBufferSize`
         // and pass it to willDecrypt(), most likely it will contains MAC
-        var bytes = bytes
+        accumulated += bytes
 
-        if isLast, var finalizingWorker = worker as? FinalizingDecryptModeWorker, isLast == true {
-            bytes = try finalizingWorker.willDecryptLast(bytes: bytes)
+        // If a worker (eg CCM) can combine ciphertext + tag
+        // we need to remove tag from the ciphertext.
+        if !isLast && accumulated.count < worker.additionalBufferSize {
+            return []
         }
 
-        var plaintext = Array<UInt8>(reserveCapacity: bytes.count)
-        for chunk in Array(bytes).batched(by: blockSize) {
+        if var finalizingWorker = worker as? FinalizingDecryptModeWorker, isLast == true {
+            // will truncate suffix if needed
+            accumulated = Array(try finalizingWorker.willDecryptLast(bytes: accumulated.slice))
+        }
+
+        var processedBytesCount = 0
+        var plaintext = Array<UInt8>(reserveCapacity: bytes.count + worker.additionalBufferSize)
+        for chunk in accumulated.batched(by: blockSize) {
             plaintext += worker.decrypt(block: chunk)
+            processedBytesCount += chunk.count
         }
 
-        if isLast, var finalizingWorker = worker as? FinalizingDecryptModeWorker, isLast == true {
+        if var finalizingWorker = worker as? FinalizingDecryptModeWorker, isLast == true {
             plaintext = Array(try finalizingWorker.didDecryptLast(bytes: plaintext.slice))
         }
 
@@ -54,6 +64,8 @@ final class StreamDecryptor: Cryptor, Updatable {
             plaintext = padding.remove(from: plaintext, blockSize: blockSize - lastBlockRemainder)
         }
 
+        accumulated.removeFirst(processedBytesCount) // super-slow
+
         if var finalizingWorker = worker as? FinalizingDecryptModeWorker, isLast == true {
             plaintext = Array(try finalizingWorker.finalize(decrypt: plaintext.slice))
         }

+ 42 - 1
Tests/Tests/AESTests.swift

@@ -596,7 +596,7 @@ extension AESTests {
         let ciphertext: Array<UInt8> = [0x71, 0x62, 0x01, 0x5b, 0x4d, 0xac, 0x25, 0x5d]
         let expected: Array<UInt8> = [0x20, 0x21, 0x22, 0x23]
 
-        let aes = try! AES(key: key, blockMode: CCM(nonce: nonce, tagLength: 4, messageLength: ciphertext.count, additionalAuthenticatedData: aad), padding: .noPadding)
+        let aes = try! AES(key: key, blockMode: CCM(nonce: nonce, tagLength: 4, messageLength: ciphertext.count - 4, additionalAuthenticatedData: aad), padding: .noPadding)
         let decrypted = try! aes.decrypt(ciphertext)
         XCTAssertEqual(decrypted, expected, "decryption failed")
     }
@@ -613,6 +613,18 @@ extension AESTests {
         XCTAssertEqual(encrypted, expected, "encryption failed")
     }
 
+    func testAESCCMTestCase2Decrypt() {
+        let key: Array<UInt8> =        [0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f];
+        let nonce: Array<UInt8> =      [0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17]
+        let aad: Array<UInt8> =        [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f]
+        let ciphertext: Array<UInt8> = [0xd2, 0xa1, 0xf0, 0xe0, 0x51, 0xea, 0x5f, 0x62, 0x08, 0x1a, 0x77, 0x92, 0x07, 0x3d, 0x59, 0x3d, 0x1f, 0xc6, 0x4f, 0xbf, 0xac, 0xcd]
+        let expected: Array<UInt8>   = [0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f]
+
+        let aes = try! AES(key: key, blockMode: CCM(nonce: nonce, tagLength: 6, messageLength: ciphertext.count - 6, additionalAuthenticatedData: aad), padding: .noPadding)
+        let plaintext = try! aes.decrypt(ciphertext)
+        XCTAssertEqual(plaintext, expected, "encryption failed")
+    }
+
     func testAESCCMTestCase3() {
         let key: Array<UInt8> =       [0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f];
         let nonce: Array<UInt8> =     [0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b]
@@ -624,6 +636,35 @@ extension AESTests {
         let encrypted = try! aes.encrypt(plaintext)
         XCTAssertEqual(encrypted, expected, "encryption failed")
     }
+
+    func testAESCCMTestCase3Decrypt() {
+        let key: Array<UInt8> =        [0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f];
+        let nonce: Array<UInt8> =      [0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b]
+        let aad: Array<UInt8> =        [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13]
+        let ciphertext: Array<UInt8> = [0xe3, 0xb2, 0x01, 0xa9, 0xf5, 0xb7, 0x1a, 0x7a, 0x9b, 0x1c, 0xea, 0xec, 0xcd, 0x97, 0xe7, 0x0b, 0x61, 0x76, 0xaa, 0xd9, 0xa4, 0x42, 0x8a, 0xa5, 0x48, 0x43, 0x92, 0xfb, 0xc1, 0xb0, 0x99, 0x51]
+        let expected: Array<UInt8> =   [0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37]
+
+        let aes = try! AES(key: key, blockMode: CCM(nonce: nonce, tagLength: 8, messageLength: ciphertext.count - 8, additionalAuthenticatedData: aad), padding: .noPadding)
+        let plaintext = try! aes.decrypt(ciphertext)
+        XCTAssertEqual(plaintext, expected, "encryption failed")
+    }
+
+    func testAESCCMTestCase3DecryptPartial() {
+        let key: Array<UInt8> =        [0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f];
+        let nonce: Array<UInt8> =      [0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b]
+        let aad: Array<UInt8> =        [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13]
+        let ciphertext: Array<UInt8> = [0xe3, 0xb2, 0x01, 0xa9, 0xf5, 0xb7, 0x1a, 0x7a, 0x9b, 0x1c, 0xea, 0xec, 0xcd, 0x97, 0xe7, 0x0b, 0x61, 0x76, 0xaa, 0xd9, 0xa4, 0x42, 0x8a, 0xa5, 0x48, 0x43, 0x92, 0xfb, 0xc1, 0xb0, 0x99, 0x51]
+        let expected: Array<UInt8> =   [0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37]
+
+        let aes = try! AES(key: key, blockMode: CCM(nonce: nonce, tagLength: 8, messageLength: ciphertext.count - 8, additionalAuthenticatedData: aad), padding: .noPadding)
+        var decryptor = try! aes.makeDecryptor()
+
+        var plaintext = [UInt8]()
+        plaintext += try! decryptor.update(withBytes: Array(ciphertext[0..<2]))
+        plaintext += try! decryptor.update(withBytes: Array(ciphertext[2..<6]))
+        plaintext += try! decryptor.update(withBytes: Array(ciphertext[6..<32]), isLast: true)
+        XCTAssertEqual(plaintext, expected, "encryption failed")
+    }
 }
 
 extension AESTests {