Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Encrypt string in Flutter and Decrypt in PHP

I am trying to send encrypted data from my Flutter application to my PHP server, but I am encountering issues with decryption on the PHP server. I am using the Encrypt package in Dart to encrypt the data with the AES encryption algorithm and then sending it to the PHP server, where I am using OpenSSL to decrypt the data.

Here is the Dart code that I am using to encrypt the data:

import 'package:encrypt/encrypt.dart' as encrypt;
void main() async {
   var plainText='test';
   final key = encrypt.Key.fromUtf8('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA');
   final iv  = encrypt.IV.fromUtf8('AAAAAAAAAAAAAAAA');

   final encrypter = encrypt.Encrypter(encrypt.AES(key));

   final encrypted = encrypter.encrypt(plainText, iv: iv);

   print(encrypted.base64);
}

This code outputs "VBnTmnNX14Sbxqu99PMtWw==".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

On the PHP side, I am using the following code to decrypt the data:

// The encrypted string
$encrypted = "VBnTmnNX14Sbxqu99PMtWw==";

// The encryption key and initialization vector (IV)
$key = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
$iv = "AAAAAAAAAAAAAAAA";

// Decrypt the string
$decrypted = openssl_decrypt(base64_decode($encrypted), 'AES-192-CBC', $key, OPENSSL_RAW_DATA, $iv);

// Output the decrypted string
echo var_dump($decrypted);

And this outputs "bool(false)" which means the encryption has failed.

Why does it fail, any idea ?

>Solution :

The key used is 32 bytes, so AES-256 must be applied on the PHP side. Also, the Dart side automatically uses CTR mode (equivalent to SIC mode, which is the default on the Dart side), requiring AES-256-CTR on the PHP side (instead of AES-192-CBC).

Be aware that the Dart code applies PKCS#7 padding (which is actually not required for a stream cipher mode like CTR). On the PHP side, padding is implicitly disabled for CTR. Therefore, the padding bytes are not removed. The correct fix is to disable padding for CTR on the Dart side (see here, section No/zero padding).

Also note that the key and IV used (as well as a static IV) are vulnerabilities (unless they were chosen that way for testing purposes only).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading