I want to create a method in c# that will accept my unique email or username and will return me a unique string just like youtube's video id (https://www.youtube.com/watch?v=_MSYfOYFF14). I can't simply use GUID because I want to generate a unique string against every user and it will remain same for that user each time I hit that method. So is that possible anyhow?
3 Answers
1) Use the MD5 to get the byte array
2) Convert the byte array to string
3) Remove last two character
using System.Security.Cryptography; //... private string GenerateUniqueString(string input ) { using (MD5 md5 = MD5.Create()) { byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(input)); var res = Convert.ToBase64String(hash); return res.Substring(0, res.Length - 2); } } 3 Comments
If it is not going to be exposed to someone else then it can be human readable. Stated that username or password is unique, that means that also combination of these values concatenated with some character (that can not be used in email and username) must be unique. The result is then very simple:
var uniqueString = $"{uniqueName}|{uniqueEmail}"; Comments
Simple example of hashing together multiple strings.
public static string Hash(bool caseInsensitive, params string[] strs) { using (var sha256 = SHA256.Create()) { for (int i = 0; i < strs.Length; i++) { string str = caseInsensitive ? strs[i].ToUpperInvariant() : strs[i]; byte[] bytes = Encoding.UTF8.GetBytes(str); byte[] length = BitConverter.GetBytes(bytes.Length); sha256.TransformBlock(length, 0, length.Length, length, 0); sha256.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } sha256.TransformFinalBlock(new byte[0], 0, 0); var hash = sha256.Hash; return Convert.ToBase64String(hash); } } There is a caseInsensitive parameter, because [email protected] is equivalent to [email protected] (and quite often [email protected] is equivalent to all of them). Note how I'm encoding the strings: I'm prepending before each string the length of the encoded string (in UTF8). In this way "Hello", "World" is differento from "Hello World", because one will be converted to something similar to 5Hello5World while the other will be "11Hello World".
Usange:
string base64hash = Hash(true, "Donald Duck", "[email protected]"); Note that thanks to the params keyword, the Hash method can accept any number of (string) parameters.
GetHashCode()to be anything near unique. See this answer for the hash functions @xanatos is referring to: stackoverflow.com/questions/800685/…Convert.ToBase64Stringfor example) and you are done..ToUpperInvariant(), to remove differences between upper and lower case