encryptTextWithKey function

String encryptTextWithKey(
  1. String text,
  2. String secret
)

Encrypts text under secret, returning a hex envelope.

Implementation

String encryptTextWithKey(String text, String secret) {
  final rnd = Random.secure();
  final salt =
      Uint8List.fromList(List.generate(_saltLen, (_) => rnd.nextInt(256)));
  final iv = Uint8List.fromList(List.generate(_ivLen, (_) => rnd.nextInt(256)));
  final key = _deriveKey(secret, salt);

  final gcm = GCMBlockCipher(AESEngine())
    ..init(true, AEADParameters(KeyParameter(key), 128, iv, Uint8List(0)));
  final body = gcm.process(Uint8List.fromList(utf8.encode(text))); // ct | tag

  final blob = Uint8List(_saltLen + _ivLen + body.length)
    ..setAll(0, salt)
    ..setAll(_saltLen, iv)
    ..setAll(_saltLen + _ivLen, body);
  return HEX.encode(blob);
}