What's the best way to create a short hash, similar to what tiny Url does?

前端 未结 13 1307
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 09:10

I\'m currently using MD5 hashes but I would like to find something that will create a shorter hash that uses just [a-z][A-Z][0-9]. It only needs to be around 5-

13条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 09:44

    Is your goal to create a URL shortener or to create a hash function?

    If your goal is to create a URL shortener, then you don't need a hash function. In that case, you just want to pre generate a sequence of cryptographically secure random numbers, and then assign each url to be encoded a unique number from the sequence.

    You can do this using code like:

    using System.Security.Cryptography;
    
    const int numberOfNumbersNeeded = 100;
    const int numberOfBytesNeeded = 8;
    var randomGen = RandomNumberGenerator.Create();
    for (int i = 0; i < numberOfNumbersNeeded; ++i)
    {
         var bytes = new Byte[numberOfBytesNeeded];
         randomGen.GetBytes(bytes);
    }
    

    Using the cryptographic number generator will make it very difficult for people to predict the strings you generate, which I assume is important to you.

    You can then convert the 8 byte random number into a string using the chars in your alphabet. This is basically a change of base calculation (from base 256 to base 62).

提交回复
热议问题