Skip to content
Advertisement

How to encrypt XOR hex string 32 in PHP

I’m trying to encrypt some of my passwords using the XOR encryption algorithm. I tested it on CyberChef but I don’t know how to convert it from PHP. I look forward to helping. Thanks a lot. XOR HEX string 32

Advertisement

Answer

It helps to start with the basic data structures involved.

Your objective is to use a secret key to transform your plain text — the message you wish to keep secret — into encrypted text. By definition your plain text is easy for an adversary to understand, and your encrypted text is not.

Then, the rest of your objective is to use the key to transform the encrypted text back into plain text. XOR is a symmetric cipher: it uses exactly the same key to encrypt and to decrypt.

Basic data structures

You have text strings like ATTACK for example.

You have arrays like

array( 65, 84, 84, 65, 67, 75)

And you have base 64 encoded strings like

base64_encode( "ATTACK" ); //QVRUQUNL

Your data structures

Let’s say your message is ATTACK. (This kind of crypto started with military applications, of course.) That’s an array of numbers. Your php example converts your message into an array of ASCII character values. This little bit of code does that. It uses the ord() function to convert a letter into a number, called a codepoint. Run it.

$plaintext = 'ATTACK';
$plaintextASCII = [];
foreach( str_split( $plaintext ) as $letter) {
  $plaintextAscii[] = ord( $letter );
}
print_r( $plaintextAscii );

It does the same thing as this line of code from your example, but using an explicit loop rather than the array_map() shortcut.

return array_map('ord', str_split($text));

Then you can mangle that array of character values. The XOR cipher is a way to do that.

Finally you convert it back to a string using the chr() function.

$encryptedString = '';
foreach ( $plaintextAscii as $codepoint ) {
  $encryptedString .= chr( $codepoint );
}

But, because you mangled your codepoints to encrypt them, this $encryptedString contains non-printable characters. So you cannot just paste the string into an email or something like that. Instead, you must encode the string using only printable characters.

base64_encode( $encryptedString );

That’s the encrypted message. To decrypt it you reverse the process.

That should get you started understanding this example code.

Pro tip when trying to understand an algorithm, don’t try to use open-source packages. Instead, look at their code and copy the interesting lines into your own sample code.

Pro tip get a decent debugger program so you can step through your code.

Online security tip do not, repeat not, use this kind of encryption to store peoples’ passwords online. It’s not secure enough to slow down cybercreeps. php has a really good set of password-hashing functions. Read about them here.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement