Skip to content

Commit dc431bb

Browse files
committed
Merge pull request #180 from defuse/v1-encoding
Version 1.x - Cache-timing safety
2 parents 399fc4c + ce7b510 commit dc431bb

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

src/Crypto.php

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -700,10 +700,14 @@ public static function binToHex($bin_string)
700700
$hex = '';
701701
$len = self::ourStrlen($bin_string);
702702
for ($i = 0; $i < $len; ++$i) {
703-
$c = \ord($bin_string[$i]) & 0xf;
704-
$b = \ord($bin_string[$i]) >> 4;
705-
$hex .= \chr(87 + $b + ((($b - 10) >> 8) & ~38));
706-
$hex .= \chr(87 + $c + ((($c - 10) >> 8) & ~38));
703+
$chunk = unpack('C', self::ourSubstr($bin_string, $i, 1));
704+
$c = $chunk[1] & 0xf;
705+
$b = $chunk[1] >> 4;
706+
$hex .= pack(
707+
'CC',
708+
(87 + $b + ((($b - 10) >> 8) & ~38)),
709+
(87 + $c + ((($c - 10) >> 8) & ~38))
710+
);
707711
}
708712
return $hex;
709713
}
@@ -722,8 +726,10 @@ public static function hexToBin($hex_string)
722726
$hex_len = self::ourStrlen($hex_string);
723727
$state = 0;
724728

729+
$chunk = \unpack('C*', $hex_string);
725730
while ($hex_pos < $hex_len) {
726-
$c = \ord($hex_string[$hex_pos]);
731+
++$hex_pos;
732+
$c = $chunk[$hex_pos];
727733
$c_num = $c ^ 48;
728734
$c_num0 = ($c_num - 10) >> 8;
729735
$c_alpha = ($c & ~32) - 55;
@@ -739,8 +745,7 @@ public static function hexToBin($hex_string)
739745
} else {
740746
$bin .= \chr($c_acc | $c_val);
741747
}
742-
$state = $state ? 0 : 1;
743-
++$hex_pos;
748+
$state ^= 1;
744749
}
745750
return $bin;
746751
}

0 commit comments

Comments
 (0)