Przeglądaj źródła

Fix ChaCha20 implementation. #179

Marcin Krzyżanowski 9 lat temu
rodzic
commit
f73a1624f7

+ 13 - 1
CryptoSwiftTests/ChaCha20Tests.swift

@@ -67,7 +67,19 @@ final class ChaCha20Tests: XCTestCase {
             }
         }
     }
-    
+
+    func testVector1Py() {
+        let key:[UInt8] = [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]
+        let iv:[UInt8]  = [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]
+        let expected:[UInt8] = [0x76,0xB8,0xE0,0xAD,0xA0,0xF1,0x3D,0x90,0x40,0x5D,0x6A,0xE5,0x53,0x86,0xBD,0x28,0xBD,0xD2,0x19,0xB8,0xA0,0x8D,0xED,0x1A,0xA8,0x36,0xEF,0xCC,0x8B,0x77,0x0D,0xC7,0xDA,0x41,0x59,0x7C,0x51,0x57,0x48,0x8D,0x77,0x24,0xE0,0x3F,0xB8,0xD8,0x4A,0x37,0x6A,0x43,0xB8,0xF4,0x15,0x18,0xA1,0x1C,0xC3,0x87,0xB6,0x69,0xB2,0xEE,0x65,0x86]
+        let message = [UInt8](count: expected.count, repeatedValue: 0)
+
+        print(message.count)
+
+        let encrypted = try! ChaCha20(key: key, iv: iv)!.encrypt(message)
+        XCTAssertEqual(encrypted, expected, "Ciphertext failed")
+    }
+
     func testChaCha20Performance() {
         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]

+ 4 - 9
Sources/CryptoSwift/ChaCha20.swift

@@ -52,9 +52,8 @@ final public class ChaCha20 {
         }
         
         var x = input
-        
-        var i = 10
-        while (i  > 0) {
+
+        for _ in 0..<10 {
             quarterround(&x[0], &x[4], &x[8], &x[12])
             quarterround(&x[1], &x[5], &x[9],  &x[13])
             quarterround(&x[2], &x[6], &x[10], &x[14])
@@ -63,18 +62,14 @@ final public class ChaCha20 {
             quarterround(&x[1], &x[6], &x[11], &x[12])
             quarterround(&x[2], &x[7], &x[8],  &x[13])
             quarterround(&x[3], &x[4], &x[9],  &x[14])
-            i -= 2
         }
 
         var output = [UInt8]()
         output.reserveCapacity(16)
 
         for i in 0..<16 {
-            x[i] = x[i] &+ input[i]            
-            output.appendContentsOf([UInt8((x[i] & 0xFFFFFFFF) >> 24),
-                       UInt8((x[i] & 0xFFFFFF) >> 16),
-                       UInt8((x[i] & 0xFFFF) >> 8),
-                       UInt8((x[i] & 0xFF) >> 0)])
+            x[i] = x[i] &+ input[i]
+            output.appendContentsOf(x[i].bytes().reverse())
         }
 
         return output;