encrypt static method

String encrypt(
  1. String input, {
  2. int key = 3,
})

Encrypts a given input string using the Caesar Cipher algorithm.

The encryption preserves the case (uppercase/lowercase) of the original characters. Non-alphabetic characters (numbers, spaces, symbols) are included in the output unchanged.

Parameters:

  • input: The string to be encrypted.
  • key: The number of positions to shift each letter. Defaults to 3 if not provided. Must be an integer between 0 and 25.

Throws ArgumentError if:

  • The input string is empty or contains only whitespace.
  • The key is outside the valid range (0-25).

Returns: A String representing the encrypted (ciphertext) version of the input.

Implementation

static String encrypt(String input, {int key = 3}) {
  if (input.trim().isEmpty) throw ArgumentError('Input cannot be empty');
  if (key < 0 || key > 25) throw ArgumentError('Key must be between 0 - 25');
  final encryptedText = StringBuffer();

  for (int i = 0; i < input.length; i++) {
    final char = input[i];
    final isUpperCase = char == char.toUpperCase();
    final lowerChar = char.toLowerCase();

    if (_lowercaseAlphabet.contains(lowerChar)) {
      final currentIndex = _lowercaseAlphabet.indexOf(lowerChar);
      final shiftedIndex = (currentIndex + key) % 26;
      var shiftedChar = _lowercaseAlphabet[shiftedIndex];
      if (isUpperCase) shiftedChar = shiftedChar.toUpperCase();
      encryptedText.write(shiftedChar);
    } else {
      encryptedText.write(input[i]);
    }
  }

  return encryptedText.toString();
}