I want to cypher / uncypher binary data from PHP to Dart (and dart to PHP) in AES256.
My code is working for text data, but not for binary data. Can anyone help me to solve this problem ?
- In the code below, if you uncomment //text="hello", the cypher text is the same, and also uncyphered : it works!.
- If I keep the comment, so working with binary data : for l_group_id variable, cyphered text is not the same in php and dart (and so the uncyphered result)
Here is my code :
PHP :
$_key = 'MySecretKeyForEncryptionAndDecry'; // 32 chars
$_iv = 'helloworldhelloW'; // 16 chars
$_method = 'aes-256-cbc';
$l_group_id = 1540980342;
$text = pack ("N", $l_group_id);
echo "Cypher : ".(($l_group_id >> 24) & 0xFF)." ".(($l_group_id >> 16) & 0xFF)." ".(($l_group_id >> 8) & 0xFF)." ".(($l_group_id) & 0xFF)."<br/>";
//$text = "hello";
$msg1 = openssl_encrypt($text, $_method, $_key, 0, $_iv);
$msg2 = openssl_decrypt($msg1, $_method, $_key, 0, $_iv);
echo "Cypher text : $msg1<br>";
echo "UnCypher text : $msg2<br/>";
Dart :
var key = encrypt.Key.fromUtf8('MySecretKeyForEncryptionAndDecry'); //32 chars
var iv = IV.fromUtf8('helloworldhelloW'); //16 chars
int l_group_id = 1540980342;
Uint8List tab = new Uint8List (13);
tab[0] = ((l_group_id >> 24) & 0xFF);
tab[1] = ((l_group_id >> 16) & 0xFF);
tab[2] = ((l_group_id >> 8) & 0xFF);
tab[3] = ((l_group_id & 0xFF));
String text = String.fromCharCodes(tab);
//text = "hello";
// encrypt
final encrypter = Encrypter(AES(key, mode: AESMode.cbc));
final encrypted = encrypter.encrypt(text, iv: iv);
String msg1 = encrypted.base64;
// decrypt
final msg2 = encrypter.decrypt(Encrypted.fromBase64(msg1), iv: iv);
debugPrint("msg1 : $msg1 - msg2 : $msg2");
Thank you for your help
2
Answers
The solution (thank you Richard)
Your binary length seems to be incorrect (13 vs 4). It’s easier to use
ByteData
too.