Added Atbash Cipher! (#136)

This commit is contained in:
Aryansh B 2023-10-10 09:12:42 +05:30 committed by GitHub
parent 599577bf9a
commit 53d6cd64ea
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 66 additions and 0 deletions

39
Ciphers/AtbashCipher.php Normal file
View File

@ -0,0 +1,39 @@
<?php
/**
* Encrypt a message using the Atbash Cipher.
* The Atbash Cipher is a simple substitution cipher where each letter in the plaintext is
* replaced with its corresponding letter from the end of the alphabet (reverse alphabet).
* Non-alphabet characters are not modified.
*
* @param string $plainText The plaintext to encrypt.
* @return string The encrypted message.
*/
function atbash_encrypt($plainText)
{
$result = '';
$plainText = strtoupper($plainText);
for ($i = 0; $i < strlen($plainText); $i++) {
$char = $plainText[$i];
if (ctype_alpha($char)) {
$offset = ord('Z') - ord($char);
$encryptedChar = chr(ord('A') + $offset);
} else {
$encryptedChar = $char; // Non-alphabet characters remain unchanged
}
$result .= $encryptedChar;
}
return $result;
}
/**
* Decrypt a message encrypted using the Atbash Cipher.
* Since the Atbash Cipher is its own inverse, decryption is the same as encryption.
*
* @param string $cipherText The ciphertext to decrypt.
* @return string The decrypted message.
*/
function atbash_decrypt($cipherText)
{
return atbash_encrypt($cipherText); // Decryption is the same as encryption
}

View File

@ -1,6 +1,7 @@
# List of all files
## Ciphers
* [Atbashcipher](./Ciphers/AtbashCipher.php)
* [Caesarcipher](./Ciphers/CaesarCipher.php)
* [Monoalphabeticcipher](./Ciphers/MonoAlphabeticCipher.php)
* [Morsecode](./Ciphers/MorseCode.php)
@ -88,6 +89,7 @@
## Tests
* Ciphers
* [Atbashciphertest](./tests/Ciphers/AtbashCipherTest.php)
* [Cipherstest](./tests/Ciphers/CiphersTest.php)
* [Monoalphabeticciphertest](./tests/Ciphers/MonoAlphabeticCipherTest.php)
* [Morsecodetest](./tests/Ciphers/MorseCodeTest.php)

View File

@ -0,0 +1,25 @@
<?php
use PHPUnit\Framework\TestCase;
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../Ciphers/AtbashCipher.php';
class AtbashCipherTest extends TestCase
{
public function testEncryptionAndDecryption()
{
$plainText = "HELLO";
$encryptedText = atbash_encrypt($plainText);
$decryptedText = atbash_decrypt($encryptedText);
$this->assertEquals($plainText, $decryptedText);
}
public function testWithNonAlphabetCharacters()
{
$plainText = "HELLO, WORLD!";
$encryptedText = atbash_encrypt($plainText);
$decryptedText = atbash_decrypt($encryptedText);
$this->assertEquals($plainText, $decryptedText);
}
}