decryptTextWithKey function

String decryptTextWithKey(
  1. String hexEnvelope,
  2. String secret
)

Decrypts a hex envelope produced by encryptTextWithKey. Throws on a wrong key or tampered ciphertext (GCM auth failure).

Implementation

String decryptTextWithKey(String hexEnvelope, String secret) {
  final blob = Uint8List.fromList(HEX.decode(hexEnvelope));
  if (blob.length < _saltLen + _ivLen + 16) {
    throw const FormatException('Credential envelope too short');
  }
  final salt = blob.sublist(0, _saltLen);
  final iv = blob.sublist(_saltLen, _saltLen + _ivLen);
  final body = blob.sublist(_saltLen + _ivLen);
  final key = _deriveKey(secret, salt);

  final gcm = GCMBlockCipher(AESEngine())
    ..init(false, AEADParameters(KeyParameter(key), 128, iv, Uint8List(0)));
  return utf8.decode(gcm.process(body));
}