Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XOR string in PHP with key

Tags:

php

I need to XOR a string/text in PHP the base64 encode it, but something goes wrong:

<?php

$mustget = 'Kw4SCQ==';
$string = 'Josh';

echo("Must get: " . $mustget . "\n");
echo("We got: " . base64_encode(xor_this($string)) . "\n");

function xor_this($text) {
    $key = 'frtkj';
    $i = 0;
    $encrypted = '';
    foreach (str_split($text) as $char) {
        $encrypted .= chr(ord($char) ^ ord($key{$i++ % strlen($key)}));
    }
    return $encrypted;
}

?>

I get the following result, but I need to get the "$mustget" one:

Must get: Kw4SCQ==
We got: LB0HAw==

What do I do wrong?

like image 574
bsteo Avatar asked Dec 14 '12 09:12

bsteo


People also ask

What is an XOR key?

XOR Encryption is an encryption method used to encrypt data and is hard to crack by brute-force method, i.e generating random encryption keys to match with the correct one.

Can you decrypt XOR?

This operation is sometimes called modulus 2 addition (or subtraction, which is identical). With this logic, a string of text can be encrypted by applying the bitwise XOR operator to every character using a given key. To decrypt the output, merely reapplying the XOR function with the key will remove the cipher.

Which cipher uses XOR?

Simply put, XOR (pronounced “exclusive or”) cipher is an additive cypher. It is based on the XOR operation (also known as the exclusive disjunction) in logic. As a logical operation, XOR is also called modulus 2 addition. In XOR operation, the output is true when the inputs differ.

What is XOR in AES?

The simple XOR cipher isn't used in production because it is impractical to use keys that are the same length as the message body. However, the XOR is still extremely useful. In fact, it is used in almost all symmetric encryption algorithms. XOR is the primary operation in the “add round key” step of AES-256.


1 Answers

$mustget = 'Kw4SCQ==';

$key = 'frtkj';
$key_length = strlen($key);

$encoded_data = base64_decode($mustget);

$result = '';

$length = strlen($encoded_data);
for ($i = 0; $i < $length; $i++) {
    $tmp = $encoded_data[$i];

    for ($j = 0; $j < $key_length; $j++) {
        $tmp = chr(ord($tmp) ^ ord($key[$j]));
    }

    $result .= $tmp;
}

echo $result; // Josh

http://ideone.com/NSIe7K

I'm sure you can reverse it and create a function, that "crypts" the data ;-)

like image 158
zerkms Avatar answered Sep 22 '22 14:09

zerkms