|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * Encrypts a plaintext using the Vigenère cipher. |
| 5 | + * (https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher) |
| 6 | + * |
| 7 | + * @param string $plaintext The plaintext to be encrypted. |
| 8 | + * @param string $key The encryption key. |
| 9 | + * @return string The encrypted text. |
| 10 | + */ |
| 11 | +function vigenere_encrypt($plaintext, $key): string |
| 12 | +{ |
| 13 | + // Convert the input to uppercase for consistency |
| 14 | + $plaintext = strtoupper($plaintext); |
| 15 | + $key = strtoupper($key); |
| 16 | + $keyLength = strlen($key); |
| 17 | + $encryptedText = ""; |
| 18 | + for ($i = 0; $i < strlen($plaintext); $i++) { |
| 19 | + $char = $plaintext[$i]; |
| 20 | + if (ctype_alpha($char)) { |
| 21 | + // Calculate the shift based on the key |
| 22 | + $shift = ord($key[$i % $keyLength]) - ord('A'); |
| 23 | + // Apply the Vigenère encryption formula |
| 24 | + $encryptedChar = chr(((ord($char) - ord('A') + $shift) % 26) + ord('A')); |
| 25 | + // Append the encrypted character to the result |
| 26 | + $encryptedText .= $encryptedChar; |
| 27 | + } else { |
| 28 | + // If the character is not alphabetic, leave it unchanged |
| 29 | + $encryptedText .= $char; |
| 30 | + } |
| 31 | + } |
| 32 | + return $encryptedText; |
| 33 | +} |
| 34 | + |
| 35 | +/** |
| 36 | + * Decrypts a ciphertext using the Vigenère cipher. |
| 37 | + * |
| 38 | + * @param string $ciphertext The ciphertext to be decrypted. |
| 39 | + * @param string $key The decryption key. |
| 40 | + * @return string The decrypted text. |
| 41 | + */ |
| 42 | +function vigenere_decrypt($ciphertext, $key): string |
| 43 | +{ |
| 44 | + $ciphertext = strtoupper($ciphertext); |
| 45 | + $key = strtoupper($key); |
| 46 | + $keyLength = strlen($key); |
| 47 | + $decryptedText = ""; |
| 48 | + for ($i = 0; $i < strlen($ciphertext); $i++) { |
| 49 | + $char = $ciphertext[$i]; |
| 50 | + if (ctype_alpha($char)) { |
| 51 | + // Calculate the shift based on the key |
| 52 | + $shift = ord($key[$i % $keyLength]) - ord('A'); |
| 53 | + // Apply the Vigenère decryption formula |
| 54 | + $decryptedChar = chr(((ord($char) - ord('A') - $shift + 26) % 26) + ord('A')); |
| 55 | + // Append the decrypted character to the result |
| 56 | + $decryptedText .= $decryptedChar; |
| 57 | + } else { |
| 58 | + // If the character is not alphabetic, leave it unchanged |
| 59 | + $decryptedText .= $char; |
| 60 | + } |
| 61 | + } |
| 62 | + return $decryptedText; |
| 63 | +} |
0 commit comments