flutterencryptiondartaes

How to generate 256-AES CBC key with PKCS5 padding key in Dart


I need to figure out how to generate a random 256 AES CBC key with PKCS5 padding in Dart for my Flutter project. I've been able to accomplish it in Java using this:

    public static SecretKey generateSecretKey() {
        KeyGenerator generator;
        try {
            generator = KeyGenerator.getInstance("AES/CBC/PKCS5Padding");
            generator.init(256); // The AES key size in number of bits (256)

            return generator.generateKey();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

In dart I've gotten as far as this (broken/unfinished code) using PointyCastle

  static generateSecretKey() {
    AESFastEngine aes = AESFastEngine();
    KeyParameter keyParameter = KeyParameter();
    aes.init(true, keyParameter);
    CBCBlockCipher cbc = CBCBlockCipher(aes);
  }

I'm using RSA 4096 keys for exchanging the AES 256 key. In the client side, I only use the public key for encrypting the generated AES key


Solution

  • @James Reinstate Monica Polk

    Apparently dart provides this for you: https://www.scottbrady91.com/Dart/Generating-a-Crypto-Random-String-in-Dart

    This seems to be a good solution for generating an AES 256 bit key.