# Code – Simple XOR encryption for PHP

Last night, after watching this episode of Computerphile, I decided to throw a simple XOR encryption algorithm together. This kind of simple XOR encryption isn’t really secure so use this only for educational purposes. If you want to have better ways to do encryption I would recommend to use PGP or GnuPG which uses key pairs (a public and a private key) instead of a single phrase.

That being said, these two simple functions are all that’s needed for this to work.

```/**
* Encrypts a text with a supplied key using a simple xor algorithm
* @param \$plainText
* @param \$key
* @return string
*/
function encrypt(\$plainText, \$key) {
\$output = "";
\$keyPos = 0;
//loop over the plaintext message
for (\$p = 0; \$p < strlen(\$plainText); \$p++) {
//make sure to reset keyPos to 0 if at end of key length
if (\$keyPos > strlen(\$key) - 1) {
\$keyPos = 0;
}
//do a bitwise XOR between current character in the plaintext message and the current character in the key
\$char = \$plainText[\$p] ^ \$key[\$keyPos];

//convert the ascii value for the encrypted character to 8-bit binary (with leading zero)
//convert the binary to a hex value
\$hex = dechex(bindec(\$bin));
//pad the hex value with leading zero if only one character, 0x00 to 0xFF
//add the hex value to the output
\$output .= strtoupper(\$hex);
\$keyPos++;
}
//return the encoded string
return \$output;
}

/**
* Decrypts an encrypted text with a supplied key using a simple xor algorithm
* @param \$encryptedText
* @param \$key
* @return string
*/
function decrypt(\$encryptedText, \$key) {
\$output = "";
//split the hex values to an array where each value is between 0x00 and 0xFF
\$hex_arr = explode(" ", trim(chunk_split(\$encryptedText, 2, " ")));

\$keyPos = 0;
//loop over each value in the hex array
for (\$p = 0; \$p < sizeof(\$hex_arr); \$p++) {
//reset the keyPos if at end of key length
if (\$keyPos > strlen(\$key) - 1) {
\$keyPos = 0;
}
//XOR the the current character of the key with the current character belonging to the ascii value of the hex value, e.g. 0x41 for "A" or 0x6D for "m" and so on
\$char = chr(hexdec(\$hex_arr[\$p])) ^ \$key[\$keyPos];

//add decrypted character to the output
\$output .= \$char;
\$keyPos++;
}
//return the decrypted message
return \$output;
}
```

See the code in action here.

This site uses Akismet to reduce spam. Learn how your comment data is processed.