Reputation: 27
I have a problem, why the result of xor p [i] with k is 00000238. It should be 00000110.
<?php
$Ciphertext = array();
$C = array();
$iv = 0;
$Kunci = "U";
$spsi= " ";
$Plaintext =$spsi."S";
$c0 = sprintf("%08d",
decbin($iv));
$key = dechex(ord($Kunci)) $k=sprintf("%08d",decbin(hexdec($key)));
$C[0]=$c0;
$P = array();
for($i =1;$i<strlen($Plaintext); $i++){
$P[$i] = dechex(ord($Plaintext[$i]));
$P[$i] = sprintf("%08d",decbin(hexdec($P[$i])));
$C[$i]=sprintf("%08d",(intval($P[$i])^intval($C[$i-1])));
$C[$i]=sprintf("%08d",(intval($C[$i])^intval($k)));
//$C[$i] = (bindec($C[$i]))<<1;
//if ($C[$i]>255)$C[$i]-=255;
//$C[$i] = sprintf("%08d", decbin($C[$i]));
//$Ciphertext[$i] = strtoupper(str_pad(dechex(bindec($C[$i])),2,"0",STR_PAD_LEFT));
}
echo "<br/>";
print_r($P);
echo "<br/>";
print_r($C);
echo "<br/>";
print_r($Ciphertext);
//echo implode(",", $P);
?>
And output :
Array ( [1] => 01010011 ) Array ( [0] => 00000000 [1] => 00000238 ) Array ( )
I want to make a program like in the picture link. https://i.sstatic.net/mcBol.png
I want to fetch these values in this manner:
P1: 01010011
C0: 00000000
C1: XOR of P1 and C0
C1: 01010101
K: 01010101
C1: XOR of C1 and K
P2: 01100000
C1: 00001100
C2: XOR of P2 and C1
C2: 01111110
K: 01010101
C2: XOR of C2 and K
etc...
Upvotes: 1
Views: 79
Reputation: 5520
<?php
$p = array(
'01010011',
'01110000',
'01100001',
'01110010'
);
$controlbits = get_controlbits($p);
function get_controlbits(array $p) {
$k = '01010101';
$c = array('00000000');
$c_key = 1;
foreach($p as $p_item) {
$prev_c = $c[$c_key-1];
//XOR of $p_item and previous $c[$c_key-1]
$c[$c_key] = _xor($prev_c, $p_item);
//XOR of current $c with $k
$c[$c_key] = _xor($c[$c_key], $k);
//Shift left bit
$c[$c_key] = bitshift_left($c[$c_key]);
$c_key++;
}
return $c;
}
function bitshift_left($text){
$text = substr($text, 1,7) . '0';
return $text;
}
//From https://stackoverflow.com/questions/14365032/xor-binary-in-php
function _xor($text,$key){
for($i=0; $i<strlen($text); $i++){
$text[$i] = intval($text[$i])^intval($key[$i]);
}
return $text;
}
output with code:
echo '<pre>';
print_r($controlbits);
echo '</pre>';
output result:
Array
(
[0] => 00000000
[1] => 00001100
[2] => 01010010
[3] => 11001100
[4] => 11010110
)
Upvotes: 1