Search code examples
javascriptrubyhashmd5radix

Hash code which contains more than 16 characters?


I would like to apply a hash code solution on my webpage which is more compact than MD5 and SHA-1, because I want to use them as keys in a JSON hash table.

Or equivalently: how can I convert a hexadecimal MD5 hash to a higher base number system? The higher the better, till the words can be used as keys in a JSON hash. For example instead of:

"684591beaa2c8e2438be48524f555141" hexadecimal MD5 hash I would prefer "668e15r60463kya64xq7umloh" which is a base 36 number and the values are equal.

I made the calculation in Ruby:

"684591beaa2c8e2438be48524f555141".to_i(16).to_s(36)
=> 668e15r60463kya64xq7umloh

Because it handles the big decimal value of the hexadecimal MD5 hash (138600936100279876740703998180777611585)

Unlike JavaScript, in JavaScript I get a float value, which is rounded. So I get the same 36-base value for different MD5 hashes.


Solution

  • Ruby

    You could return base64digest directly :

    require 'digest'
    
    Digest::MD5.hexdigest 'your_page'
    #=> "a6b580481008e60df9350de170b7e728"
    
    p Digest::MD5.base64digest 'your_page'
    #=> "prWASBAI5g35NQ3hcLfnKA=="
    

    Javascript

    If you already have a hex string, a comment from this previous answer seems to work fine :

    btoa("a6b580481008e60df9350de170b7e728".match(/\w{2}/g).map(function(a){return String.fromCharCode(parseInt(a, 16));} ).join(""))
    #=> "prWASBAI5g35NQ3hcLfnKA=="