Elmar Naude - 1 year ago 62
PHP Question

# PHP encryption algorithm

I am working on a web server that receives encrypted data from an ESP8266 module. I have managed to get the encryption and decryption fully functional in C, however PHP is giving me a small problem. I have narrowed the problem the these two functions in the decryption (AES encrypt/decrypt is used):

This function performs multiplication with the Galo's field:

function gmul(\$a, \$b) {
\$p = 0;
\$counter;
\$hi_bit_set;
for(\$counter = 0; \$counter < 8; \$counter++) {
if((\$b & 1) == 1)
\$p ^= \$a;
\$hi_bit_set = (\$a & 0x80);
\$a <<= 1;
if(\$hi_bit_set == 0x80)
\$a ^= 0x1b;
\$b >>= 1;
}
return \$p;}

This will mix the columns with the use of multiplication of the Galos field:

function invMixColumns(\$w){
\$i;
\$j;
\$k;
\$temp;

for(\$j = 0; \$j < 4; \$j++){
for(\$k =0; \$k < 4; \$k++){
\$temp[\$j][\$k] = \$w[\$j][\$k];
}
}

for(\$i = 0; \$i < 4; \$i++)
{
\$w[0][\$i] = gmul(\$temp[0][\$i],14) ^ gmul(\$temp[3][\$i],9) ^ gmul(\$temp[2][\$i],13) ^ gmul(\$temp[1][\$i],11);
\$w[1][\$i] = gmul(\$temp[1][\$i],14) ^ gmul(\$temp[0][\$i],9) ^ gmul(\$temp[3][\$i],13) ^ gmul(\$temp[2][\$i],11);
\$w[2][\$i] = gmul(\$temp[2][\$i],14) ^ gmul(\$temp[1][\$i],9) ^ gmul(\$temp[0][\$i],13) ^ gmul(\$temp[3][\$i],11);
\$w[3][\$i] = gmul(\$temp[3][\$i],14) ^ gmul(\$temp[2][\$i],9) ^ gmul(\$temp[1][\$i],13) ^ gmul(\$temp[0][\$i],11);
}

return \$w;

}

The invMixColumns function recieves the following input (hex)

[ff][6][20][d5]
[10][bd][eb][4c]
[28][59][4e][69]
[6e][84][79][7]

And the expected output should be (hex): (Tested in C)

[dd][77][53][34]
[15][f1][99][3f]
[43][e4][de][7d]
[22][04][e8][81]

The actual output in PHP is close but there is a prefix hex value as seen here (hex):

[7dd][377][753][434]
[415][2f1][499][63f]
[643][3e4][6de][57d]
[522][204][5e8][781]

It is possibly a syntax error that I made. Any Ideas? Is there a way to simply remove the first hex number, for example 0x7dd -> 0xdd ? Thanks in advance.

Answer Source

By using the & (bitwise and operator) I managed to get the output that I wanted.

0xd77 & 0xff = 0x77