1

What's the absolute simplest way to generate a URL safe checksum for a string in .NET? I'll use this checksum as a lookup and it will be part of and URL and therefore needs to be URL safe.

GetHashCode would have been perfekt for me if it only generated the same hash for the same string on different version of .NET ... Basically what I need is a url shortener I guess

Community
  • 1
  • 1
Riri
  • 11,501
  • 14
  • 63
  • 88
  • Must the checksum be unique? Must it be unguessable? A cryptographic hash fulfills all that, but might be a bit long. – CodesInChaos Aug 09 '11 at 10:53
  • Doesn't have to be unique. Basically i just want a way to get a id for a long string and that that hash is consistent for the same sting over different version of .NET etc (GetHashCode isn't). As short and guessable as possible is just fine ;) – Riri Aug 09 '11 at 11:21

2 Answers2

2

Create an MD5 checksum (or any other) then use

HttpServerUtility.UrlTokenEncode

to encode the string.

--- EDITED to reflect comments

Fadrian Sudaman
  • 6,405
  • 21
  • 29
  • I was hoping to not use UrlEncode as it has problems when using in a URL http://stackoverflow.com/questions/906754/bad-request-400-for-httputility-urlencoded-url-segments – Riri Aug 09 '11 at 11:17
  • What you need then is HttpServerUtility.UrlTokenEncode. Get the checksum and fit it straight to this method which will give you an URL safe string without all the sign characters that is encoded. You will decode it the same way using HttpServerUtility.UrlTokenDecode. I will update the answer to avoid confusion – Fadrian Sudaman Aug 09 '11 at 11:38
  • That worked! The id is long and ugly but at least it works ;). Thanks – Riri Aug 09 '11 at 11:49
0

Base64 is not url safe. It includes the chars "+", "=" and "/".

A SHA1 (or MD5) hash only contains the characters 0-9a-f and is therefor url safe without url encoding or base64.

Example method that returns a 40 char lowercase SHA1 hash from a string:

public static string GetSHA1Hash(string input)
{
    byte[] bytes = System.Text.Encoding.Default.GetBytes(input ?? string.Empty);
    bytes = System.Security.Cryptography.SHA1.Create().ComputeHash(bytes);
    System.Text.StringBuilder sb = new System.Text.StringBuilder(40);
    for (int i = 0, l = bytes.Length; i < l; i++)
        sb.Append(bytes[i].ToString("x2"));
    return sb.ToString();
}
David Brockman
  • 567
  • 4
  • 6