What are the differences between the ROT13 and Caesar Algorithm in PHP encryption?
The ROT13 algorithm is a simple letter substitution cipher that replaces a letter with the letter 13 positions down the alphabet. The Caesar algorithm, on the other hand, allows for a customizable shift value for letter substitution. In PHP, the ROT13 algorithm is commonly implemented using the str_rot13() function, while the Caesar algorithm can be implemented by manually shifting the letters based on a specified key.
// Implementing ROT13 encryption in PHP
$text = "Hello, World!";
$encrypted_text = str_rot13($text);
echo $encrypted_text;
// Implementing Caesar encryption with a shift of 3 in PHP
function caesarEncrypt($text, $shift){
$result = "";
$length = strlen($text);
for($i = 0; $i < $length; $i++){
$char = $text[$i];
if(ctype_alpha($char)){
$offset = ord(ctype_upper($char) ? 'A' : 'a');
$result .= chr(fmod((ord($char) + $shift - $offset), 26) + $offset);
} else {
$result .= $char;
}
}
return $result;
}
$text = "Hello, World!";
$encrypted_text = caesarEncrypt($text, 3);
echo $encrypted_text;