decrypt static method

String decrypt(
  1. String input,
  2. int key
)

Decrypts a given input string (ciphertext) using the Caesar Cipher algorithm.

This method iterates through each character of the input:

  • Alphabetic characters (A-Z, a-z) are shifted backward by the specified key. Their original case (uppercase or lowercase) is preserved.
  • Non-alphabetic characters are included in the output without any changes.

Parameters:

  • input: The string to be decrypted (ciphertext).
  • key: The number of positions that was originally used for encryption. This must be the same key. Must be an integer between 0 and 25 (inclusive).

Throws an ArgumentError if:

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

Returns: A String representing the decrypted (plaintext) version of the input.

Implementation

static String decrypt(String input, int key) {
  if (input.trim().isEmpty) throw ArgumentError('Input cannot be empty');
  if (key < 0 || key > 25) throw ArgumentError('Key must be between 0 - 25');
  final decryptedText = 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();
      decryptedText.write(shiftedChar);
    } else {
      decryptedText.write(input[i]);
    }
  }

  return decryptedText.toString();
}