'Swift - AES base64 + md5 decryption

I'm trying to decrypt a message sent from our server.

Both our server and my Android client side uses the encryption code from here:
https://gist.github.com/jafetsanchez/1080133

  • The server uses the CS code to encrypt the message
  • My android client uses the java code to decrypt the message

I want to add the decryption feature to my iPhone client app with Swift. However I'm not sure how to do it with iOS tools.

I'm using CryptoSwift

Here's what I tried to do:

    let iVector: [UInt8] = [
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    ]
    
   let encryptedMessage = "encrypted_message_encrypted_message_encrypted_message_encrypted_message_"
    
    let password = "passwordpassword"

    
    do {
        let aes = try AES(key: password, iv: String(bytes: iVector, encoding: .utf8)!, padding: .pkcs7) // aes128
        let decryptedText = try aes.decrypt(encryptedMessage.bytes)
        let data = Data(bytes: decryptedText, count: decryptedText.count)

        if let string = String(data: data, encoding: .utf8) {
            
            print(string)
        } else {
            
            print("not a valid UTF-8 sequence")
        }
    } catch { }

Right now i'm getting error: CryptoSwift.AES.Error.dataPaddingRequired

In addition, I'm not sure how to combine the MD5 hashing there.



Solution 1:[1]

Try This..

static func encryptMessage(message: String, encryptionKey: String, iv: String) -> String? {
   if let aes = try? AES(key: encryptionKey, iv: iv),
      let encrypted = try? aes.encrypt(Array<UInt8>(message.utf8)) {
      return encrypted.toHexString()
   }
   return nil
}
static func decryptMessage(encryptedMessage: String, encryptionKey: String, iv: String) -> String? {
   if let aes = try? AES(key: encryptionKey, iv: iv),
      let decrypted = try? aes.decrypt(Array<UInt8>(hex: encryptedMessage)) {
      return String(data: Data(decrypted), encoding: .utf8)
   }
   return nil
}

Solution 2:[2]

You need to go with something along the lines:

let password = "passwordpassword".bytes.md5()
let aes = try AES(key: password, blockMode: CBC(iv: iVector), padding: .pkcs7)

When dealing with data, it's good to carefully follow the format of the data, whether it's a String, or bytes, or Base64.

Solution 3:[3]

let base64String = Data(cipher).base64EncodedString(); //Encode (cipher data from CryptoSwift)

let text = base64String.decryptBase64ToString(cipher: aes); //Decode Base64 also decrypt data 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ben Rockey
Solution 2 Marcin
Solution 3 a442509097