Source
The whole tool is the function below. It runs client-side; the full script
is at /assets/rotn.js.
JavaScript
function rotLetter(code, n) {
if (code >= 65 && code <= 90) return 65 + (((code - 65 + n) % 26) + 26) % 26; // A-Z
if (code >= 97 && code <= 122) return 97 + (((code - 97 + n) % 26) + 26) % 26; // a-z
return code;
}
function rotDigit(code, n) {
if (code >= 48 && code <= 57) return 48 + (((code - 48 + n) % 10) + 10) % 10; // 0-9
return code;
}
// Rotate letters by n; if nNum is truthy, also rotate digits by nNum.
// Every other character passes through unchanged.
function rotN(str, n, nNum) {
var out = "";
for (var i = 0; i < str.length; i++) {
var code = str.charCodeAt(i);
code = rotLetter(code, n);
if (nNum) code = rotDigit(code, nNum);
out += String.fromCharCode(code);
}
return out;
}
ROT13 is rotN(text, 13). Numeric ROT5 is
rotN(text, 0, 5). To decrypt ROTn, use
rotN(text, 26 - n).
Original PHP
The site previously ran this equivalent PHP function.
function rot_n($string, $n, $n_numeric = FALSE)
{
$result = "";
$length = strlen($string);
for ($i = 0; $i < $length; $i++)
{
$ascii = ord($string[$i]);
$rotated = $ascii;
# Capital letters are 65 to 90
if ($ascii > 64 && $ascii < 91)
{
$rotated = $rotated + $n;
$rotated > 90 && $rotated += -90 + 64;
$rotated < 65 && $rotated += -64 + 90;
}
# Lowercase letters are 97 to 122
elseif ($ascii > 96 && $ascii < 123)
{
$rotated = $rotated + $n;
$rotated > 122 && $rotated += -122 + 96;
$rotated < 97 && $rotated += -96 + 122;
}
# Numeric digits are 48 to 57
if ($n_numeric AND $ascii > 47 AND $ascii < 58)
{
$rotated = ($rotated - 48 + $n_numeric) % 10 + 48;
}
$result .= chr($rotated);
}
return $result;
}