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