Home » Php » encryption – PHP: Simple, Validate if string is hex?

encryption – PHP: Simple, Validate if string is hex?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have no clue how to validate this string. I am simply supplying an IV for an encryption, but can find no 1is_hex()1 or similar function, I can’t wrap my head around it! I read on a comment in the php documentation (user contrib. notes) this:

if($iv == dechex(hexdec($iv))) {
  //True
} else {
  //False
}

But that doesn’t seem to work at all.. It only says false.
If it helps my input of my IV would be this:

92bff433cc639a6d
How to&Answers:

Use function : ctype_xdigit

<?php
$strings = array('AB10BC99', 'AR1012', 'ab12bc99');
foreach ($strings as $testcase) {
    if (ctype_xdigit($testcase)) {
        echo "The string $testcase consists of all hexadecimal digits.\n";
    } else {
        echo "The string $testcase does not consist of all hexadecimal digits.\n";
    }
}
?> 

The above example will output:

  • The string AB10BC99 consists of all hexadecimal digits.
  • The string AR1012 does not consist of all hexadecimal digits.
  • The string ab12bc99 consists of all hexadecimal digits.

Answer:

Is there any reason not to match against a simple RE like “[0-9A-Fa-f]+”? (edit: possibly with a ‘^’ at the beginning and ‘$’ at the end to assure you’ve matched the whole string).

Answer:

Another way without ctype or regex:

$str = 'string to check';

if (trim($str, '0..9A..Fa..f') == '') {
    // string is hexadecimal
}

Answer:

Add the case-insensitive ‘i’ flag

preg_match('/^[0-9a-f]+$/i', ...

Answer:

The perfect way to check HEX string works from PHP 4 and above.

<?php
function is_hex($hex_code) {
        return @preg_match("/^[a-f0-9]{2,}$/i", $hex_code) && !(strlen($hex_code) & 1);
}
?>

Answer:

Your input is too large. From the PHP manual of dexhex

The largest number that can be converted is 4294967295 in decimal
resulting to “ffffffff”

So you’ll be better off using a RegEx, which have already been supplied here by others.

Answer:

This is also possible and quite simple

$a="affe";  //is_hex
$b="a0bg";   //is_not_hex

if(is_numeric('0x'.$a)) echo 'is_hex';
else echo 'is_not_hex';

if(is_numeric('0x'.$b)) echo 'is_hex';
else echo 'is_not_hex';