Search code examples
iosswiftflutterencryptionaes

How to get compatible encryption version in flutter as in iOS


I am working on iOS and flutter application together. There is encryption of data happening on both the sides. Below is the iOS encryption code which is already live,

func encryption(encryptionKey: String) -> String{
        if(self.isEmpty){
            return ""
        }else{
            let key = encryptionKey
            
            let dataBytes : [UInt8] = Array(self.utf8)
            let keyBytes : [UInt8] = Array(key.utf8)
            
            do {
                let encryptedData = try AES(key: keyBytes, blockMode: ECB(), padding: .pkcs7).encrypt(dataBytes)
                let encodedString = Data(encryptedData).base64EncodedString()
                return encodedString
            } catch let error {
                print(error)
                return ""
            }
        }

Below is the flutter encryption code that I am working on now (Using encrypt.dart package),

final key = Key.fromBase64("Some_Key");
final iv = IV.fromLength(16));

final encrypter = Encrypter(AES(key, mode: AESMode.ecb, padding: 'PKCS7'));
final encrypted = encrypter.encrypt(someString, iv: iv); //IV is ignored in ECB mode

The issue here is the encrypted string that I am getting in flutter must be the same as iOS which is not the case. Could someone help me out in getting a compatible encryption version in flutter? Kindly help...


Solution

  • I finally resolved it myself. Posting the answer over here hoping it helps someone.

    I had to change the below line,

    from

    final key = Key.fromBase64("Some_Key");
    

    to

    final key = Key.fromUtf8("Some_Key");
    

    That't it. It works!!