如何在AES 256中对PHP到Dart / flutter的二进制数据进行加解密

ux6nzvsh  于 2023-03-15  发布在  PHP
关注(0)|答案(2)|浏览(128)

我想在AES 256中加密/解密从PHP到Dart(以及从Dart到PHP)的二进制数据。我的代码可以处理文本数据,但不能处理二进制数据。有人能帮我解决这个问题吗?

  • 在下面的代码中,如果取消注解//text=“hello”,则加密文本是相同的,并且也是未加密的:它起作用了!
  • 如果我保留注解,那么使用二进制数据:对于l_group_id变量,php和dart中的加密文本是不同的(因此未加密的结果也是不同的)

下面是我的代码:
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");

谢谢你的帮忙

ubby3x7f

ubby3x7f1#

二进制长度似乎不正确(13 vs 4)。使用ByteData也更容易。

final lGroupId = 1540980342;
  // php pack N => 32 bit unsigned big endian => 4 bytes
  // the 3rd parameter is optional - the default *is* big
  final lGroupIdBytes = Uint8List(4)
    ..buffer.asByteData().setUint32(0, lGroupId, Endian.big);

  print(lGroupIdBytes); // should match the values from PHP

  // now use encrypter.encryptBytes(lGroupIdBytes, iv: iv);
  // this assumes the encrypter defaults to PKCS7 padding
mqkwyuun

mqkwyuun2#

解决方案(谢谢理查德)

var key = encrypt.Key.fromUtf8('MySecretKeyForEncryptionAndDecry'); //32 chars
var iv = IV.fromUtf8('helloworldhelloW'); //16 chars

int l_group_id = 1540980342;
// php pack N => 32 bit unsigned big endian => 4 bytes
// the 3rd parameter is optional - the default *is* big
final lGroupIdBytes = Uint8List(4)
  ..buffer.asByteData().setUint32(0, l_group_id, Endian.big);

String text = String.fromCharCodes(lGroupIdBytes);

//text = "hello";

// encrypt
final encrypter = Encrypter(AES(key, mode: AESMode.cbc));
final encrypted = encrypter.encryptBytes (lGroupIdBytes, iv: iv);
String msg1 = encrypted.base64;

// decrypt
final msg2 = encrypter.decryptBytes(Encrypted.fromBase64(msg1), iv: iv);

debugPrint("msg1 : $msg1 - msg2 : $msg2");

相关问题