Represent MD5 hash as an integer

前端 未结 8 1911
Happy的楠姐
Happy的楠姐 2021-02-05 09:42

In my user database table, I take the MD5 hash of the email address of a user as the id.

Example: email(example@example.org) = id(d41d8cd98f00b204e9800998ecf8427e)

8条回答
  •  爱一瞬间的悲伤
    2021-02-05 10:12

    There are good reasons, stated by others, for doing it a different way.

    But if what you want to do is convert an md5 hash into a string of decimal digits (which is what I think you really mean by "represent by an integer", since an md5 is already an integer in string form), and transform it back into the same md5 string:

    function md5_hex_to_dec($hex_str)
    {
        $arr = str_split($hex_str, 4);
        foreach ($arr as $grp) {
            $dec[] = str_pad(hexdec($grp), 5, '0', STR_PAD_LEFT);
        }
        return implode('', $dec);
    }
    
    function md5_dec_to_hex($dec_str)
    {
        $arr = str_split($dec_str, 5);
        foreach ($arr as $grp) {
            $hex[] = str_pad(dechex($grp), 4, '0', STR_PAD_LEFT);
        }
        return implode('', $hex);
    }
    

    Demo:

    $md5 = md5('example@example.com');
    echo $md5 . '
    '; // 23463b99b62a72f26ed677cc556c44e8 $dec = md5_hex_to_dec($md5); echo $dec . '
    '; // 0903015257466342942628374306682186817640 $hex = md5_dec_to_hex($dec); echo $hex; // 23463b99b62a72f26ed677cc556c44e8

    Of course, you'd have to be careful using either string, like making sure to use them only as string type to avoid losing leading zeros, ensuring the strings are the correct lengths, etc.

提交回复
热议问题