Implement ROT13 with PHP

encryption, php, rot13

Solution

Here is a working implementation, without using the nested loop. You also don't need to split the string into an array, since you can index individual characters just like an array with strings in PHP.

You need to know that ASCII upper-case characters range from 65 - 99, and lower-case characters range from 97 - 122. If the current character is in one of those ranges, add 13 to its ASCII value. Then, you check if you should have rolled over to the beginning of the alphabet. If you should've rolled over, subtract 26.

$string = "Vs lbh nfxrq Oehpr Fpuarvre gb qrpelcg guvf, ur'q pehfu lbhe fxhyy jvgu uvf ynhtu.";

for ($i = 0, $j = strlen( $string); $i < $j; $i++) 
{
    // Get the ASCII character for the current character
    $char = ord( $string[$i]); 

    // If that character is in the range A-Z or a-z, add 13 to its ASCII value
    if( ($char >= 65  && $char <= 90) || ($char >= 97 && $char <= 122)) 
    {
        $char += 13; 

        // If we should have wrapped around the alphabet, subtract 26
        if( $char > 122 || ( $char > 90 && ord( $string[$i]) <= 90)) 
        {
            $char -= 26;
        }
    }
    echo chr( $char);
}

This produces:

If you asked Bruce Schneier to decrypt this, he'd crush your skull with his laugh.

Problem

I found a string after reading funny things about Jon Skeet, and I guessed that it was in ROT13. Before just checking my guess, I thought I'd try and decrypt it with PHP. Here's what I had: ``` $string = "Vs lbh nfxrq Oehpr Fpuarvre gb qrpelcg guvf, ur'q pehfu lbhe fxhyy jvgu uvf ynhtu."; $tokens = str_split($string); for ($i = 1; $i <= sizeof($tokens); $i++) { $char = $tokens[$i-1]; for ($c = 1; $c <= 13; $c++) { $char++; } echo $char; } ``` My string comes back as `AIaf you aasakaead ABruacae Sacahnaeaiaer to adaeacrypt tahais, ahae'ad acrusah your sakualal waitah ahais alaauagah.` My logic seems quite close, but it's obviously wrong. Can you help me with it?

Original source