Simple XOR Encryption Algorithm
Jul 23, 09
XOR Encryption
XOR Encryption is a simple symmetric cipher in use in many applications where security is not a defined requirement. Exclusive-OR ( XOR ) encryption is almost unbreakable through brute force methods, although it is susceptible to patterns, it requires that both encryptor and decryptor have access to the encryption key, but the encryption algorithm although very simple is nearly unbreakable .
How it works
The XOR Encryption works by applying the Exclusive-OR operator ( ^ ) to every character of a string, thus changing it value. To decrypt the output it only requires that you reapply the key to the output resulting the plain text.
- A ^ 0 = A
- A ^ A = 0
- (B ^ A) ^ A = B ^ 0 = B
void encrypt(char string[], char key[])
{
int string_len = strlen(string);
int key_length = strlen(key);
int i,position;
for(i = 0; i < string_len; i++)
{
position = i % key_length;
string[i] = (char)((int)string[i] ^ (int)key[position]);
}
}
Also here is a php implementation as well :
function encryption($string, $key)
{
$string_len = strlen($string);
$key_length = strlen($key);
for( $i = 0; $i < $string_len; $i++)
{
$position = $i % $key_length;
$replace = ord($string[$i]) ^ ord($key[$position]);
$string[$i] = chr($replace);
}
return $string;
}
Advantages of using XOR
- Simple to implement ( requires only a few lines of code )
- Pretty secure against attacks ( especially if key length == string length )
Hello Andrey.
I found your little tutorial quite interesting, but i didnt really understand it 100%, so maybe if you had time ,and would like to make another example in php, where you actually use it in a script/system.
Best Regards and merry christmas from Denmark
Oliver Wang
Let’s say that you have a password stored in a variable named $password and we would like to encrypt it with the key “1qazxsw2″ the way we do it is
$password = encryption($password, “1qazxsw2″);
However if you would echo $password you will see some unrecognizable characters the proper way to use it would be :
//encryption
$password = base64_encrypt(encryption($password, “1qazxsw2″));
echo $password; // encrypted password
//decryption
$password = encryption(base64_decrypt($password), “1qazxsw2″));
echo $password; //original password
Interesting blog you got here but I can’t seem to find the RSS button.
It is at the left of the search field, thanks.
-Andrey
very good information you write it very clean.
It’s a wonderful article, thanks!