-1

My PHP server uses the encrypt as follows.

openssl_encrypt('data', 'AES-256-CBC', '1234567890123456', 0, '1234567890123456')

the result is adVh7c/vcyascTS0Z669IA==.

My dart server uses encrypt package as follows.

import 'package:encrypt/encrypt.dart' as encrypt;
Encrypter(AES(encryptKey, mode: AESMode.cbc)).encrypt('data', iv: '1234567890123456').base64
final encrypt.Key encryptKey = encrypt.Key.fromUtf8('1234567890123456');
       final encrypt.IV encryptIvKey = encrypt.IV.fromUtf8('1234567890123456');
       final encrypt.Encrypter encrypter = encrypt.Encrypter(encrypt.AES(encryptKey, mode: encrypt.AESMode.cbc));
       print(encrypter.encrypt('data', iv: encryptIvKey).base64);

The result is KQjJ76efmVlgGKDsj6dCog==.

These result values are different. I saw the cipher method of PHP. If I change the cipher method in the PHP server from

AES-256-CBC

to

aes-128-cbc // or aes-128-cbc-hmac-sha1, aes-128-cbc-hmac-sha256

The result will be KQjJ76efmVlgGKDsj6dCog==. (same as the result from the dart server) But editing files in the PHP server is the last choice. What I can do in the dart server to make the result the same as the result from the PHP server (AES-256-CBC method)?

How to use the AES-256-CBC method in encrypt package? If I must edit files in the PHP server, what method I should use? The aes-128-cbc, aes-128-cbc-hmac-sha1 and aes-128-cbc-hmac-sha256 give the same result. Or some method better than this and it is available in encrypt package as follows in this image. Suggestion me, please. enter image description here

  • 3
    `aes-256-cbc` requires a 32 bytes key. The key in the PHP code is too short and is *implicitly* padded with `0x00` values. In the Dart code this must be done *explicitly*, e.g. with `'1234567890123456'.padRight(32, '\x00')`. – Topaco Nov 20 '22 at 09:22
  • 2
    Regarding `aes-128-cbc`, `aes-128-cbc-hmac-sha1` and `aes-128-cbc-hmac-sha256`: Apply `aes-128-cbc`, s. [here](https://stackoverflow.com/a/73386073/9014097). – Topaco Nov 20 '22 at 09:26
  • Thank you too much. I never know about this. I only know the key in `encrypt.Key.fromUtf8('1234567890123456');` can be 16, 24, or 32 bytes but I never know that the cipher method requires n bytes. Do you want to add an answer to this? I will check for you. Thank you for your new knowledge. – Sittiphan Sittisak Nov 20 '22 at 13:18

1 Answers1

0

The summary from the comment in my post by @Topaco. The aes-256-cbc cipher method requires a 32 bytes key. Use the key with a string length of 32 or use the padRight(32, '\x00') function.

example:

final encrypt.Key encryptKey = encrypt.Key.fromUtf8('1234567890123456'.padRight(32, '\x00'));

Regarding aes-128-cbc, aes-128-cbc-hmac-sha1 and aes-128-cbc-hmac-sha256: Apply aes-128-cbc(ref)