function shift($char, $key) { // Convert upper to lower. if (ord($char) >= 65 && ord($char) <= 90) { $temp = strtolower($char); $char = $temp; } $code = letterToNum($char); $shifted = $code + $key; // If it isn't a letter. if (ord($char) >= 97 && ord($char) <= 122) { if ($key < 0) { if ($shifted < 0) { $coded = 26 + $shifted; $newCh = NumToLetter($coded); } else { $coded = $shifted; $newCh = NumToLetter($coded); } return $newCh; } else { if ($shifted > 25) { $coded = $shifted % 26; $newCh = NumToLetter($coded); } else { $coded = $shifted; $newCh = NumToLetter($coded); } } return $newCh; } else { return $char; } }
function encode($plaintext, $key, $sizeOfKey) { $encryptedText = ""; $cleanText = clean($plaintext); $paddedText = padText($cleanText, $key, $sizeOfKey); $paddedTextArray = explode(",", $paddedText); $keyArray = explode(",", $key); array_splice($keyArray, 0, 1); // Moves through text one block at a time, converts it to the 0-25 value system, // multiples key row against block as a column, mods by 26, then adds 97 to convert // back to ascii letter. for ($x = 0; $x < count($paddedTextArray); $x += $sizeOfKey) { $plainBlock = array(); // Collects a block and converts to the 0-25 value. for ($y = 0; $y < $sizeOfKey; $y++) { array_push($plainBlock, $paddedTextArray[$x + $y]); } // Traverses the whole key, one row after the next. for ($p = 0; $p < $sizeOfKey * $sizeOfKey; $p += $sizeOfKey) { $letterTotal = 0; // Collects the sum of products of a key row and plaintext block column. for ($z = 0; $z < $sizeOfKey; $z++) { $letterTotal += $keyArray[$p + $z] * $plainBlock[$z]; } // Converts 0-25 value of encrypted letter back into ascii equivalent. if ($letterTotal >= 0) { $encryptedText .= NumToLetter($letterTotal % 26); } else { $result = $letterTotal; while ($result < 0) { $result += 26; } $encryptedText .= NumToLetter($result); } } } return $encryptedText; }