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: Encrypting the letter 'A' with a shift parameter of 2. A => C.
The code below is working somewhat decently. It's able to encrypt/decrypt the text I enter, as long as it's between certain ASCII values.
The values 65-90 in ASCII is uppercase letters, and 97-122 is lowercase letters. My problem is if my shift parameter is so large, that I exceed these intervals.
Let's say I have the letter 'A' which I want to encrypt with a shift parameter of 100. If I try this, the letter 'A' becomes this character (http://www.theasciicode.com.ar/ascii-codes/spanish-enye-capital-letter-n-tilde-enie-uppercase-ascii-code-165.gif), which can't show up in my browser, and is converted into a weird question mark.
My question is, what are my options for avoiding these weird symbols? Is it possible to make it so it only includes letters (uppercase and lowercase) and maybe numbers as well?
I hope you can help me. I will be online all day, so if you need any more information, just ask :-)
My form field:
<form method="post">
<input type="text" name="textCaesarEncrypt" autocomplete="off" placeholder="Indtast tekst">
<input type="number" name="shiftCaesarEncrypt" autocomplete="off">
<label>Krypter</label>
<input type="radio" name="caesarEncryptOrDecrypt" value="caesarEncrypt">
<label>Dekrypter</label>
<input type="radio" name="caesarEncryptOrDecrypt" value="caesarDecrypt">
<input type="submit" name="submitCaesarEncrypt" value="Videre">
My PHP:
<?php
$caesarEncryptOrDecrypt = $_POST ["caesarEncryptOrDecrypt"];
if (!empty($_POST['textCaesarEncrypt']) AND
!empty($_POST['shiftCaesarEncrypt'])){
$string = $_POST['textCaesarEncrypt'];
$shift = $_POST['shiftCaesarEncrypt'];
$shiftedString = "";
if($caesarEncryptOrDecrypt == "caesarEncrypt") {
for ($i = 0; $i < strlen($string); $i++) {
$ascii = ord($string[$i]);
$shiftedChar = chr($ascii + $shift);
$shiftedString .= $shiftedChar;
}
echo $shiftedString;
}
if($caesarEncryptOrDecrypt == "caesarDecrypt") {
for ($i = 0; $i < strlen($string); $i++) {
$ascii = ord($string[$i]);
$shiftedChar = chr($ascii - $shift);
$shiftedString .= $shiftedChar;
}
echo $shiftedString;
}
}
?>