SecureCookie constructor

SecureCookie({
  1. dynamic key,
  2. SecurityMode? mode,
  3. bool useEncryption = false,
  4. bool useSigning = false,
})

Factory constructor to create a new SecureCookie with the provided key and security mode.

key - The base64 encoded key (should be at least 32 bytes for AES) or Uint8List mode - The security mode to use (defaults to both encryption and signing)

Implementation

factory SecureCookie({
  dynamic key,
  SecurityMode? mode,
  bool useEncryption = false,
  bool useSigning = false,
}) {
  // Determine mode based on encryption/signing flags
  final effectiveMode =
      mode ??
      (useEncryption && useSigning
          ? SecurityMode.both
          : useEncryption
          ? SecurityMode.aesOnly
          : useSigning
          ? SecurityMode.hmacOnly
          : SecurityMode.both);

  final keyBytes = key != null
      ? (key is String
            ? base64.decode(key.replaceFirst('base64:', ''))
            : key as Uint8List)
      : _generateKeyFromEnv();

  // Ensure key is long enough for selected mode
  if (effectiveMode != SecurityMode.hmacOnly && keyBytes.length < 32) {
    throw ArgumentError('Key must be at least 32 bytes for AES encryption');
  }

  // Create HMAC if needed
  final hmacKey =
      (effectiveMode == SecurityMode.hmacOnly ||
          effectiveMode == SecurityMode.both)
      ? keyBytes
      : null;

  // Create AES encrypter if needed
  final aesKey =
      (effectiveMode == SecurityMode.aesOnly) ||
          (effectiveMode == SecurityMode.both)
      ? Uint8List.fromList(keyBytes.sublist(0, 32))
      : null;

  return SecureCookie._(hmacKey, aesKey, effectiveMode);
}