Search code examples
flutterdartencryptionaes

How to store AES Private key in flutter project?


I do not want show any person who open AESEncryption class. Where do i store this key in project especially android platform.

class AESEncryption {
    static final _key = Key.fromUtf8('My private key');
    static final _iv = IV.fromLength(16);

  static String getEncryptedMessage(String plainText) {
    final encrypter = Encrypter(AES(_key));
    final encrypted = encrypter.encrypt(plainText, iv: _iv);
    return encrypted.base64;
  }
  static String getDecryptedMessage(String cipherText) {
    final encrypter = Encrypter(AES(_key));
    final decrypted = encrypter.decrypt(Encrypted.from64(cipherText), iv: _iv);
    return decrypted;
  }
}

Solution

  • There are many things you could do here but what I've done - which is lightweight and works quite well - is create an env.dart file where I put various environment variables I want to keep private. I then have env.dart at the base level of my project and add an entry for it to .gitignore (or the equivalent if you're not using git). So in then in the file that defines AESEncryption I'd import the env file like below:

    /// env.dart
    final aes_private_key = 'My private key';
    
    /// Other file containing the AESEncryption class
    import 'env.dart' as env;
    
    class AESEncryption {
      static final _key = Key.fromUtf8(env.aes_private_key);
      static final _iv = IV.fromLength(16);
    
      ...
    }