You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter AES-256加密求助:与硬件设备交互解密异常

AES256-CBC-PKCS5Padding加密实现问题求助

我在实现AES加密时遇到问题,需要将加密数据发送至硬件设备,设备解密后用于相关操作(该设备与其他设备交互时解密正常)。

我希望通过自定义的password和IV生成密钥(每次操作的password和IV唯一,密钥也会相应变化),请问该如何实现?要求采用AES256 CBC PKCS5 Padding加密方式。

以下是我的Flutter代码:

class RijndaelCryptLock {
  final String password;
  final String iv;
  final KeyParameter _keyParam;
  final ParametersWithIV<KeyParameter> _params;
  final BlockCipher _cipher;

  RijndaelCryptLock(this.password, this.iv)
      : _keyParam = KeyParameter(Uint8List.fromList(utf8.encode(password))),
        _params = ParametersWithIV<KeyParameter>(
            KeyParameter(Uint8List.fromList(utf8.encode(password))),
            Uint8List.fromList(utf8.encode(iv))),
        _cipher = CBCBlockCipher(AESEngine()) {
    _cipher.init(true, _params); // true for encryption
  }

  String? encrypt(Uint8List text) {
    try {
      final paddedText = _pad(text);
      final encryptedData = _processBlocks(paddedText);
      return base64Encode(encryptedData);
    } catch (e) {
      print('Error encrypting: $e');
      return null;
    }
  }

  Uint8List _pad(Uint8List input) {
    final padLength = 16 - (input.length % 16);
    final padding = Uint8List(padLength)..fillRange(0, padLength, padLength);
    return Uint8List.fromList(input + padding);
  }

  Uint8List _processBlocks(Uint8List input) {
    final output = Uint8List(input.length);
    for (var offset = 0; offset < input.length; offset += _cipher.blockSize) {
      _cipher.processBlock(input, offset, output, offset);
    }
    return output;
  }

  Uint8List encryptData(Uint8List data, String passcodeKey, Uint8List iv) {
    final key =
        Key.fromUtf8(passcodeKey.padRight(32, '\u0000')); //Ensure 32-byte key
    final encrypter = Encrypter(AES(key, mode: AESMode.cbc, padding: 'PKCS7'));
    final encrypted = encrypter.encryptBytes(data, iv: IV(iv));
    return encrypted.bytes;
  }
}

测试用示例值

password = Q35q57i8018vM0K0QLy7Qn5qd7980F1o
iv = 3v51M0K8Q0y7Q951
secretMsgtoBeEncrypted = 2A430B254753443164656D6F6C6F303737374C4C3450493152504650594A48434E0000000067E4FB1EB8452367E4FB1FBE8D23

注:secretMsgtoBeEncrypted是存储为字符串的十六进制数据

硬件返回的解密数据

decrypted = DecryptedData in Hex 88:32 41 34 33 30 42 32 35 34 37 35 33 34 34 33 31 36 34 36 35 36 44 36 46 36 43 36 46 33 30 33 37 33 37 33 37 34 43 34 43 33 34 35 30 34 39 33 31 35 32 35 30 34 36 35 30 35 39 34 41 34 38 34 33 34 45 30 30 30 30 30 30 30 30 36 37 45 34 46 42 31 45 42 38 34 35 32 33 0

内容的提问来源于stack exchange,提问作者Yolo-cell-hash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 16:06:06