Last active
April 20, 2020 10:58
-
-
Save castroalves/923efabc61e13a6be3bd63f6299cde77 to your computer and use it in GitHub Desktop.
Solução do Pergaminho de Fasdal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Usage: run `php pergaminho.php` on Terminal | |
* | |
* @author Cadu de Castro Alves <https://github.com/castroalves> | |
*/ | |
$encrypted_message = 'VNWRWJ BQJAXW YXBBDR BJWPDN ANJU. YANLRBJVXB MNUJ YJAJ ANBBDBLRCJA X NGNALRCX MN VXACXB N RWRLRJA J MNBCADRLJX CXCJU MN OJBMJU.'; | |
$decrypted_message = 'FASDAL DE CU EH ROLA'; | |
echo decryptMessage($encrypted_message, 10); | |
echo encryptMessage($decrypted_message, 10); | |
/** | |
* Creates an array with the respective offset alphabet | |
* | |
* @param int $offset Offset of the alphabet | |
* | |
* @return array | |
*/ | |
function offsetAlphabet(int $offset): array | |
{ | |
$letters = range('A', 'Z'); | |
$total_letters = count($letters); | |
$offset_alphabet = []; | |
foreach ($letters as $index => $letter) { | |
$offset_index = $index + $offset - 1; | |
$calc_index = $total_letters - $offset_index; | |
$current_index = $calc_index > 0 ? $offset_index : abs($calc_index); | |
$offset_alphabet[$letters[$current_index]] = $letter; | |
} | |
return $offset_alphabet; | |
} | |
/** | |
* Decrypt message using the given offset | |
* | |
* @param string $message Message to decrypt | |
* @param int $offset Offset of the alphabet | |
* | |
* @return string | |
*/ | |
function decryptMessage(string $message, int $offset = 10): string | |
{ | |
$offset_alphabet = offsetAlphabet($offset); | |
return strtr(strtoupper($message), $offset_alphabet) . PHP_EOL; | |
} | |
/** | |
* Encrypt message for the given offset | |
* | |
* @param string $message Message to encrypt | |
* @param int $offset Offset of the alphabet | |
* | |
* @return string | |
*/ | |
function encryptMessage(string $message, int $offset = 10): string | |
{ | |
$offset_alphabet = array_flip(offsetAlphabet($offset)); | |
return strtr(strtoupper($message), $offset_alphabet) . PHP_EOL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment