setEncrypted method

Future<Cookie> setEncrypted(
  1. String name,
  2. String value, {
  3. String? domain,
  4. String? path,
  5. DateTime? expires,
  6. bool? httpOnly,
  7. bool? secure,
  8. int? maxAge,
})

Adds a new ciphered cookie to cookies list.

Implementation

// secretKey length must be exactly 32 bytes
Future<Cookie> setEncrypted(
  String name,
  String value, {
  String? domain,
  String? path,
  DateTime? expires,
  bool? httpOnly,
  bool? secure,
  int? maxAge,
}) async {
  final keyBytes = utf8.encode(_secretKey);
  if (keyBytes.length != 32)
    throw Exception(
        'Expected secretKey length is 32, but got: ${keyBytes.length}');
  final valueBytes = utf8.encode(value);
  final algorithm = AesGcm.with256bits(nonceLength: 12);

  final key = await algorithm.newSecretKeyFromBytes(keyBytes);
  // Encrypt
  final secretBox = await algorithm.encrypt(valueBytes, secretKey: key);
  var encryptedValue = base64Url.encode(secretBox.concatenation());

  return set(name, encryptedValue,
      domain: domain,
      path: path,
      expires: expires,
      httpOnly: httpOnly,
      secure: secure,
      maxAge: maxAge);
}