I\'m working on a page on cryptography, and have decided to include a Caesar Cipher, a method in which you shift a letter \'X\' amount of spaces left or right. Example: Encrypti
First of all, it's important to mention that Caesar-Cipher is not recommended, it's too weak, weak, weak, too weak and pretty easy to be broken.
for sure you don't want to use an encrypting system which was used before more that 2000 years
Julius Caesar: 13 July 100 BC – 15 March 44 BC)
However, The key here is in the up next formula -in the encrypting case-:
while to decrypt your encrypted data , you will need to use the next formula :
where En(x) refers to encrypted char, x = char, n = shift value;
formulas images source [wikipedia]
However this formula is pretty good for humans, but not for computers , humans only have 26 Latin character, while computers have ASCII which represented by 128, also we don't care about the case of the letter, so Hello = heLLo for us, while it is not the same with computers which represents a as 97 and A as 65.
so you will need to convert your ASCII to easy 1-26 range of character.
here i will implement a simple edit in your encrypting part, and I hope that helps you to implement the rest of decrypting part of your code.
for ($i = 0, $n = strlen($string); $i < $n; $i++) {
$char = $string[$i];
// here we are checking the character type
// to set the range which will be used later
if (ctype_upper($char)) {
$range = 65;
} else if (ctype_lower($char)) {
$range = 97;
}
// convert the ascii indexed chars into alphabetic indexed chars
$ascii = ord($char) - $range;
// the caesar folrmula based on alphabetic indexed chars
$shiftedChar = chr((($ascii + $shift) % 26) + $range);
$shiftedString .= $shiftedChar;
}
echo $shiftedString;
If you want to make sure that only alphabetic characters will be encoded, you may use ctype_alpha to check that, it's returns true if the character is alphabetic chars.
It's also important to notice that in decrypting Caesar-cipher , you will need as mentioned before to use the next formula :
$shiftedChar = chr((($ascii - $shift) % 26) + $range);
// ^ notice this
also to change your ranges as follows :
if (ctype_upper($char)) {
$range = 90; // start with Z
} else if (ctype_lower($char)) {
$range = 122; // start with z
}
another great helpful source from cs50 , this is a Caesar-cipher C tutorial , but it has the same concept.