Merge pull request #18 from RohitChattopadhyay/add/ciphers/xor_cipher

Add XOR Cipher
This commit is contained in:
Brandon Johnson 2020-10-10 23:33:42 -06:00 committed by GitHub
commit 58ed9fdae0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 46 additions and 5 deletions

View File

@ -1,10 +1,6 @@
## Ciphers
* [Caesar Cipher](https://github.com/TheAlgorithms/PHP/blob/master/ciphers/caesarCipher.php)
## String
* [Check Palindrome](https://github.com/TheAlgorithms/PHP/blob/master/String/CheckPalindrome.php)
* [Reverse String](https://github.com/TheAlgorithms/PHP/blob/master/String/ReverseString.php)
* [Reverse Words](https://github.com/TheAlgorithms/PHP/blob/master/String/ReverseWords.php)
* [Xor Cipher](https://github.com/TheAlgorithms/PHP/blob/master/ciphers/XORCipher.php)
## Searching
* [Binary Search](https://github.com/TheAlgorithms/PHP/blob/master/searches/binary_search.php)
@ -15,3 +11,8 @@
* [Merge Sort](https://github.com/TheAlgorithms/PHP/blob/master/sorting/mergeSort.php)
* [Radix Sort](https://github.com/TheAlgorithms/PHP/blob/master/sorting/radixSort.php)
* [Selection Sort](https://github.com/TheAlgorithms/PHP/blob/master/sorting/selectionSort.php)
## String
* [Check Palindrome](https://github.com/TheAlgorithms/PHP/blob/master/String/CheckPalindrome.php)
* [Reverse String](https://github.com/TheAlgorithms/PHP/blob/master/String/ReverseString.php)
* [Reverse Words](https://github.com/TheAlgorithms/PHP/blob/master/String/ReverseWords.php)

18
ciphers/XORCipher.php Normal file
View File

@ -0,0 +1,18 @@
<?php
// The XOR cipher is a type of additive cipher.
// Each character is bitwise XORed with the key.
// We loop through the input string, XORing each
// character with the key.
function xor_cipher(string $inp_string, string $key)
{
$key_len = strlen($key);
$result = array();
for ($idx = 0;$idx < strlen($inp_string);$idx++)
{
array_push($result, $inp_string[$idx] ^ $key[$idx % $key_len]);
}
return join("", $result);
}

22
tests/CipherTest.php Normal file
View File

@ -0,0 +1,22 @@
<?php
use function PHPUnit\Framework\assertEquals;
use function PHPUnit\Framework\assertFalse;
use function PHPUnit\Framework\assertNotEquals;
use function PHPUnit\Framework\assertTrue;
use PHPUnit\Framework\TestCase;
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../ciphers/XORCipher.php';
class CipherTest extends TestCase
{
public function testXor_cipher()
{
$inp_str = "test@string";
$key = "test-key";
$invalid_key = "wrong-key";
assertEquals( $inp_str, xor_cipher( xor_cipher( $inp_str , $key) , $key));
assertNotEquals( $inp_str, xor_cipher( xor_cipher( $inp_str , $key) , $invalid_key));
}
}