소스 검색

AES update. IV is required or convenience initializer should be used, then IV is default to zeroes [0x00...]. Convenience function to generate random IV.

Marcin Krzyżanowski 10 년 전
부모
커밋
134e21e98f
5개의 변경된 파일91개의 추가작업 그리고 39개의 파일을 삭제
  1. 14 14
      CryptoSwift/AES.swift
  2. 49 0
      CryptoSwift/Cipher.swift
  3. 1 1
      CryptoSwift/CipherBlockMode.swift
  4. 15 10
      CryptoSwiftTests/AESTests.swift
  5. 12 14
      README.md

+ 14 - 14
CryptoSwift/AES.swift

@@ -93,22 +93,11 @@ public class AES {
         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, 0x74, 0xe8, 0xcb, 0x8d]
     
-    public init?(key:NSData, iv:NSData? = nil, blockMode:CipherBlockMode = .CBC) {
+    public init?(key:NSData, iv:NSData, blockMode:CipherBlockMode = .CBC) {
         self.key = key
         self.blockMode = blockMode
+        self.iv = iv
         
-        var finalIV = iv
-        if (blockMode.supportIV() && iv == nil) {
-            // auto generate IV
-            var generatedIV:[Byte] = [Byte]();
-            for (var i = 0; i < key.length; i++) {
-                generatedIV.append(UInt8(truncatingBitPattern: arc4random_uniform(256)));
-            }
-            finalIV = NSData.withBytes(generatedIV)
-        }
-
-        self.iv = finalIV
-
         switch (key.length * 8) {
         case 128:
             self.variant = .aes128
@@ -121,8 +110,19 @@ public class AES {
             break
         default:
             self.variant = .unknown
-            return nil;
+            return nil
         }
+        
+        if (blockMode.requireIV() && iv.length != key.length) {
+            assertionFailure("Key and Initialization Vector must be the same length!")
+            return nil
+        }
+    }
+    
+    convenience public init?(key:NSData, blockMode:CipherBlockMode = .CBC) {
+        // default IV is all 0x00...
+        let defaultIV = NSMutableData(length: key.length)!
+        self.init(key: key, iv: defaultIV, blockMode: blockMode)
     }
     
     public class func blockSizeBytes() -> Int {

+ 49 - 0
CryptoSwift/Cipher.swift

@@ -9,9 +9,33 @@
 import Foundation
 
 public enum Cipher {
+    /**
+    ChaCha20
+    
+    :param: key Encryption key
+    :param: iv  Initialization Vector
+    
+    :returns: Value of Cipher
+    */
     case ChaCha20(key: NSData, iv: NSData)
+    /**
+    AES
+    
+    :param: key       Encryption key
+    :param: iv        Initialization Vector
+    :param: blockMode Block mode (CBC by default)
+    
+    :returns: Value of Cipher
+    */
     case AES(key: NSData, iv: NSData, blockMode: CipherBlockMode)
     
+    /**
+    Encrypt message
+    
+    :param: message Plaintext message
+    
+    :returns: encrypted message
+    */
     public func encrypt(message: NSData) -> NSData? {
         switch (self) {
             case .ChaCha20(let key, let iv):
@@ -23,6 +47,13 @@ public enum Cipher {
         }
     }
     
+    /**
+    Decrypt message
+    
+    :param: message Message data
+    
+    :returns: Plaintext message
+    */
     public func decrypt(message: NSData) -> NSData? {
         switch (self) {
             case .ChaCha20(let key, let iv):
@@ -34,4 +65,22 @@ public enum Cipher {
         }
     }
 
+    public func randomIV(key: NSData) -> [Byte] {
+        var randomIV:[Byte] = [Byte]();
+        for (var i = 0; i < key.length; i++) {
+            randomIV.append(UInt8(truncatingBitPattern: arc4random_uniform(256)));
+        }
+        return randomIV
+    }
+    
+    /**
+    Convenience function to generate Initialization Vector (IV) for given key. Use this function to generate IV for you key.
+    
+    :param: key Given key
+    
+    :returns: Random IV
+    */
+    public func randomIV(key: NSData) -> NSData {
+        return NSData.withBytes(randomIV(key))
+    }
 }

+ 1 - 1
CryptoSwift/CipherBlockMode.swift

@@ -11,7 +11,7 @@ import Foundation
 public enum CipherBlockMode {
     case ECB, CBC, CFB
     
-    func supportIV() -> Bool {
+    func requireIV() -> Bool {
         switch (self) {
         case CBC, CFB:
             return true

+ 15 - 10
CryptoSwiftTests/AESTests.swift

@@ -42,7 +42,7 @@ class AESTests: XCTestCase {
             0xd8, 0xcd, 0xb7, 0x80,
             0x70, 0xb4, 0xc5, 0x5a];
         
-        if let aes = AES(key: NSData.withBytes(aesKey), iv: nil, blockMode: .ECB) {
+        if let aes = AES(key: NSData.withBytes(aesKey), blockMode: .ECB) {
             let encrypted = aes.encrypt(NSData.withBytes(input))
             XCTAssertEqual(encrypted!, NSData.withBytes(expected), "encryption failed")
             let decrypted = aes.decrypt(encrypted!)
@@ -97,9 +97,9 @@ class AESTests: XCTestCase {
             [0xcd, 0x60, 0xe0, 0xe7],
             [0xba, 0x70, 0xe1, 0x8c]]
         
-        let substituted = AES(key: NSData.withBytes(aesKey))!.subBytes(input)
+        let substituted = AES(key: NSData.withBytes(aesKey), blockMode: .CBC)!.subBytes(input)
         XCTAssertTrue(compareMatrix(expected, substituted), "subBytes failed")
-        let inverted = AES(key: NSData.withBytes(aesKey))!.invSubBytes(substituted)
+        let inverted = AES(key: NSData.withBytes(aesKey), blockMode: .CBC)!.invSubBytes(substituted)
         XCTAssertTrue(compareMatrix(input, inverted), "invSubBytes failed")
     }
     
@@ -114,23 +114,24 @@ class AESTests: XCTestCase {
             [0xe0, 0xe1, 0xb7, 0xd0],
             [0x8c, 0x4, 0x51, 0xe7]]
         
-        let shifted = AES(key: NSData.withBytes(aesKey))!.shiftRows(input)
+        let shifted = AES(key: NSData.withBytes(aesKey), blockMode: .CBC)!.shiftRows(input)
         XCTAssertTrue(compareMatrix(expected, shifted), "shiftRows failed")
-        let inverted = AES(key: NSData.withBytes(aesKey))!.invShiftRows(shifted)
+        let inverted = AES(key: NSData.withBytes(aesKey), blockMode: .CBC)!.invShiftRows(shifted)
         XCTAssertTrue(compareMatrix(input, inverted), "invShiftRows failed")
     }
     
     func testAES_multiply() {
-        XCTAssertTrue(AES(key: NSData.withBytes(aesKey))?.multiplyPolys(0x0e, 0x5f) == 0x17, "Multiplication failed")
+        XCTAssertTrue(AES(key: NSData.withBytes(aesKey), blockMode: .CBC)?.multiplyPolys(0x0e, 0x5f) == 0x17, "Multiplication failed")
     }
     
     func testAES_expandKey() {
         let expected:[Byte] = [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: NSData.withBytes(aesKey)) {
+        if let aes = AES(key: NSData.withBytes(aesKey), blockMode: .CBC) {
             XCTAssertEqual(expected, aes.expandKey(), "expandKey failed")
+        } else {
+            XCTAssert(false, "")
         }
-        
     }
     
     func testAES_addRoundKey() {
@@ -144,9 +145,11 @@ class AESTests: XCTestCase {
             [32, 96, 160, 224],
             [48, 112, 176, 240]]
         
-        if let aes = AES(key: NSData.withBytes(aesKey)) {
+        if let aes = AES(key: NSData.withBytes(aesKey), blockMode: .CBC) {
             let result = aes.addRoundKey(input, aes.expandKey(), 0)
             XCTAssertTrue(compareMatrix(expected, result), "addRoundKey failed")
+        } else {
+            XCTAssert(false, "")
         }
     }
     
@@ -161,11 +164,13 @@ class AESTests: XCTestCase {
             [0x64, 0xbc, 0x3b, 0xf9],
             [0x15, 0x92, 0x29, 0x1a]]
         
-        if let aes = AES(key: NSData.withBytes(aesKey)) {
+        if let aes = AES(key: NSData.withBytes(aesKey), blockMode: .CBC) {
             let mixed = aes.mixColumns(input)
             XCTAssertTrue(compareMatrix(expected, mixed), "mixColumns failed")
             let inverted = aes.invMixColumns(mixed)
             XCTAssertTrue(compareMatrix(input, inverted), "invMixColumns failed")
+        } else {
+            XCTAssert(false, "")
         }
     }
 

+ 12 - 14
README.md

@@ -89,31 +89,29 @@ Some content-encryption algorithms assume the input length is a multiple of k oc
     
 Working with Ciphers
 
-	// convenience setup tuple
-	let setup = (key: keyData, iv: ivData)
-
 ChaCha20
 
-	let chacha20Encrypted = Cipher.ChaCha20(setup).encrypt(dataToEncrypt)
-	let decryptedChaCha20 = Cipher.ChaCha20(setup).decrypt(encryptedData)
+	let chacha20Encrypted = Cipher.ChaCha20(key: keyData, iv: ivData).encrypt(dataToEncrypt)
+	let decryptedChaCha20 = Cipher.ChaCha20(key: keyData, iv: ivData).decrypt(encryptedData)
 
 AES
 	
-	// padding
-	let paddedData = PKCS7(data: dataToEncrypt).addPadding(AES.blockSizeBytes())
+	// Adding padding for plaintext data is necessary for most of the cases
+	let paddedPlaintextData = PKCS7(data: dataToEncrypt).addPadding(AES.blockSizeBytes())
 	
-	// AES setup with CBC block mode and PKCS#7 data padding
-	let aesEncrypted = Cipher.AES(setup).encrypt(paddedData)
+	// Setup AES key and IV
+	let keyData = NSData.withBytes([0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00])
+	let ivData:NSData = Cipher.randomIV(keyData)
+	let encryptedData = Cipher.AES(key: keyData, iv: ivData, blockMode: .CBC).encrypt(paddedPlaintextData)
 	
 	// or
 	let aes = AES(key: keyData, iv: ivData, blockMode: .CBC) // CBC is default
-	let aesEncrypted = aes.encrypt(paddedData)
+	let encryptedData = aes?.encrypt(paddedData)
 	
-
 	// decrypt
-	let decryptedAES = Cipher.AES(setup).decrypt(encryptedData)
-	let decryptedRaw = PKCS7(data: decryptedAES).removePadding() // remove padding IF applied on encryption
-	
+	let decryptedPlaintextData = Cipher.AES(key: keyData, iv: ivData, blockMode: .CBC).decrypt(encryptedData)
+	// remove padding ONLY IF applied earlier
+	let decryptedRaw = PKCS7(data: decryptedPlaintextData).removePadding()	
 
 Using extensions