首页 > 解决方案 > 在 Dart 中使用 AES ECB 加密二进制数组

问题描述

我正在寻找一种在 Dart 中加密二进制数组的方法。我看过一些更常见的库,例如https://pub.dartlang.org/packages/encrypt,但其中许多只能处理字符串形式的 AES 密钥和数据,而不是二进制数组。

我还查看了https://github.com/PointyCastle/pointycastle,它似乎能够处理二进制数组中的 AES 密钥和数据,但我不太清楚如何正确使用它。包含数据的二进制数组始终与键长度相同,因此不需要任何填充。

到目前为止,这是我的代码:

class Encr {
    static List<int> encrCmd(List<int> inputData, List<int> aesKey) {

        Uint8List keyList = Uint8List.fromList(aesKey);
        Uint8List dataList = Uint8List.fromList(inputData);

        CipherParameters cip = new PaddedBlockCipherParameters(newKeyParameter(keylist), null);
        BlockCipher cipherImpl = new BlockCipher("AES/ECB");
        cipherImpl.init(true, cip);
        Uint8List encrypted = cipherImpl.process(dataList);
        print("encrypted data: " + encrypted.toString());
        }
}

这会导致以下错误消息:

I/flutter (55555): The following assertion was thrown while handling a gesture:
I/flutter (55555): type 'PaddedBlockCipherParameters<KeyParameter, Null>' is not a subtype of type 'KeyParameter' of 'params'

不幸的是,关于如何使用 PointyCastle 的信息并不多。有没有更好的方法来完成我想要的?

标签: dartflutterpointycastle

解决方案


您不需要 aPaddedBlockCipherParameters因为您没有使用填充密码。

尝试:

import 'dart:typed_data';

import 'package:pointycastle/api.dart';
import 'package:pointycastle/block/aes_fast.dart';
import 'package:pointycastle/block/modes/ecb.dart';

main() {
  Uint8List key = Uint8List.fromList(
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
  );

  Uint8List plainText = Uint8List.fromList(
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
  );

  BlockCipher cipher = ECBBlockCipher(AESFastEngine());

  cipher.init(
    true,
    KeyParameter(key),
  );
  Uint8List cipherText = cipher.process(plainText);
}

推荐阅读