dartflutterpointycastle

Encrypting binary array with AES ECB in Dart


I'm looking for a way to encrypt a binary array in Dart. I've had a look at some of the more common libraries such as https://pub.dartlang.org/packages/encrypt, but many of them can only handle AES keys and data in String form, not binary arrays.

I've also had a look at https://github.com/PointyCastle/pointycastle which seems to be able to handle AES keys and data in binary arrays, but I can't quite figure out how to use it properly. The binary array containing the data is always the same length as the key, so it shouldn't need any padding.

This is my code so far:

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());
        }
}

This results in the following error message:

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'

There is unfortunately not that much information on how to use PointyCastle. Is there maybe a better way to accomplish what I want?


Solution

  • You don't need a PaddedBlockCipherParameters as you aren't using a padded cipher.

    Try:

    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);
    }