Add XOR Cipher

This commit is contained in:
Rohit Chattopadhyay 2020-10-03 07:26:14 +00:00 committed by GitHub
parent fac1942b8f
commit fb39e78ce8
3 changed files with 47 additions and 4 deletions

View File

@ -1,7 +1,5 @@
## 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)
## Ciphers
* [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)
@ -12,3 +10,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));
}
}