Convert MD5 to base62 for URL

前端 未结 9 464
再見小時候
再見小時候 2020-12-30 10:43

I have a script to convert to base 62 (A-Za-z0-9) but how do I get a number out of MD5?

I have read in many places that because the number from an MD5 is bigger than

相关标签:
9条回答
  • 2020-12-30 11:36

    You can do something like this,

    $hash = md5("The data to be hashed", true);
    $ints = unpack("L*num", $hash);
    
    $hash_str = base62($ints['num1']) . base62($ints['num2']) . base62($ints['num3']) . base62($ints['num4'])
    
    0 讨论(0)
  • 2020-12-30 11:36

    As of PHP 5.3.2, GMP supports bases up to 62 (was previously only 36), so brianreavis's suggestion was very close. I think the simplest answer to your question is thus:

    function base62hash($source, $chars = 22) {
      return substr(gmp_strval(gmp_init(md5($source), 16), 62), 0, $chars);
    }
    

    Converting from base-16 to base-62 obviously has space benefits. A normal 128-bit MD5 hash is 32 chars in hex, but in base-62 it's only 22. If you're storing the hashes in a database, you can convert them to raw binary and save even more space (16 bytes for an MD5).

    Since the resulting hash is just a string representation, you can just use substr if you only want a bit of it (as the function does).

    0 讨论(0)
  • 2020-12-30 11:39

    Here is an open-source Java library that converts MD5 strings to Base62 strings https://github.com/inder123/base62

    Md5ToBase62.toBase62("9e107d9d372bb6826bd81d3542a419d6") ==> cbIKGiMVkLFTeenAa5kgO4

    Md5ToBase62.fromBase62("4KfZYA1udiGCjCEFC0l") ==> 0000bdd3bb56865852a632deadbc62fc

    The conversion is two-way, so you will get the original md5 back if you convert it back to md5:

    Md5ToBase62.fromBase62(Md5ToBase62.toBase62("9e107d9d372bb6826bd81d3542a419d6")) ==> 9e107d9d372bb6826bd81d3542a419d6

    Md5ToBase62.toBase62(Md5ToBase62.fromBase62("cbIKGiMVkLFTeenAa5kgO4")) . ==> cbIKGiMVkLFTeenAa5kgO4

    ```

    0 讨论(0)
提交回复
热议问题