|
|
@@ -95,11 +95,14 @@ ChaCha20
|
|
|
let decryptedChaCha20 = Cipher.ChaCha20(key: keyData, iv: ivData).decrypt(encryptedData)
|
|
|
|
|
|
AES
|
|
|
+
|
|
|
+Padding plaintext data is required for most of the cases (unless message can be split into chunks of block size). Nonetheless explicit padding is optional and CryptoSwift will add padding when necessary. Removing padding is necessary after decryption if applied earlier (CryptoSwift can't decide if padding was applied earlier, this is up to you). For this reason the most convenient way is always add padding before encryption and remove after decryption, as described below:
|
|
|
+
|
|
|
+
|
|
|
+ // 1. Add padding
|
|
|
+ let paddedPlaintextData = PKCS7(data: plaintextData).addPadding(AES.blockSizeBytes())
|
|
|
|
|
|
- // Adding padding for plaintext data is necessary for most of the cases
|
|
|
- let paddedPlaintextData = PKCS7(data: dataToEncrypt).addPadding(AES.blockSizeBytes())
|
|
|
-
|
|
|
- // Setup AES key and IV
|
|
|
+ // 2. Encrypt with key and random 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)
|
|
|
@@ -108,10 +111,11 @@ AES
|
|
|
let aes = AES(key: keyData, iv: ivData, blockMode: .CBC) // CBC is default
|
|
|
let encryptedData = aes?.encrypt(paddedData)
|
|
|
|
|
|
- // decrypt
|
|
|
+ // 3. decrypt with key and IV
|
|
|
let decryptedPlaintextData = Cipher.AES(key: keyData, iv: ivData, blockMode: .CBC).decrypt(encryptedData)
|
|
|
- // remove padding ONLY IF applied earlier
|
|
|
- let decryptedRaw = PKCS7(data: decryptedPlaintextData).removePadding()
|
|
|
+
|
|
|
+ // 4. remove padding ONLY IF applied earlier
|
|
|
+ let plaintextData = PKCS7(data: decryptedPlaintextData).removePadding()
|
|
|
|
|
|
Using extensions
|
|
|
|