简体   繁体   中英

What's wrong with my XOR PHP implementation?

I'm trying an XOR implementation with a Hex Key. When this code (the syntax obviously changed, but the same idea) is executed in C, and then converted to hex, the result is 44 D6 B4 7E

But when I run this code in PHP, I am getting 36 32 31 31

It's clear that an integer number is returning for each $string index, but it's not really clear WHY (to me).

Here is my PHP code:

<?php
$text = "data";
$key =  array(0x20, 0xB7, 0xC0, 0x1F);
function xor_encrypt($string, $key) {
    for($i=0; $i<strlen($string); $i++) {
        $string[$i] = ord($string[$i]) ^ $key[$i % sizeof($key)];
    }
    return $string;
}
echo xor_encrypt($text, $key);
?>

And here is the C code

BYTE m_btKey[4] = { 0x20, 0xB7, 0xC0, 0x1F };
for ( UINT i = 0; i < m_uDataLen; ++i )
    m_szData[i] ^= ( m_btKey[i % sizeof(m_btKey)] );

^ results in a number. You need to use chr() to convert it back into a character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM