forked from TheAlgorithms/PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CaesarCipher.php
executable file
·53 lines (49 loc) · 2.06 KB
/
CaesarCipher.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
<?php
/**
* Encrypt given text using caesar cipher.
*
* @param string text text to be encrypted
* @param int shift number of shifts to be applied
* @return string new encrypted text
*/
function encrypt(string $text, int $shift): string
{
$encryptedText = ''; // Empty string to store encrypted text
foreach (str_split($text) as $c) { // Going through each character
if (ctype_alpha($c)) {
$placeValue = ord($c) - ord(ctype_upper($c) ? 'A' : 'a'); // Getting value of character (i.e. 0-25)
$placeValue = ($placeValue + $shift) % 26; // Applying encryption formula
$placeValue += ord(ctype_upper($c) ? 'A' : 'a');
$newChar = chr($placeValue); // Getting new character from new value (i.e. A-Z)
$encryptedText .= $newChar; // Appending encrypted character
} else {
$encryptedText .= $c; // Appending the original character
}
}
return $encryptedText; // Returning encrypted text
}
/**
* Decrypt given text using caesar cipher.
* @param string text text to be decrypted
* @param int shift number of shifts to be applied
* @return string new decrypted text
*/
function decrypt(string $text, int $shift): string
{
$decryptedText = ''; // Empty string to store decrypted text
foreach (str_split($text) as $c) { // Going through each character
if (ctype_alpha($c)) {
$placeValue = ord($c) - ord(ctype_upper($c) ? 'A' : 'a'); // Getting value of character (i.e. 0-25)
$placeValue = ($placeValue - $shift) % 26; // Applying decryption formula
if ($placeValue < 0) { // Handling case where remainder is negative
$placeValue += 26;
}
$placeValue += ord(ctype_upper($c) ? 'A' : 'a');
$newChar = chr($placeValue); // Getting new character from new value (i.e. A-Z)
$decryptedText .= $newChar; // Appending decrypted character
} else {
$decryptedText .= $c; // Appending the original character
}
}
return $decryptedText; // Returning decrypted text
}