Guest User

Untitled

a guest
Dec 18th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. Guid g = New Guid("Mehar");
  2.  
  3. string input = "asdfasdf";
  4. using (MD5 md5 = MD5.Create())
  5. {
  6. byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(input));
  7. Guid result = new Guid(hash);
  8. }
  9.  
  10. /// <summary>
  11. /// Generates Guid based on String. Key assumption for this algorithm is that name is unique (across where it it's being used)
  12. /// and if name byte length is less than 16 - it will be fetched directly into guid, if over 16 bytes - then we compute sha-1
  13. /// hash from string and then pass it to guid.
  14. /// </summary>
  15. /// <param name="name">Unique name which is unique across where this guid will be used.</param>
  16. /// <returns>For example "{706C7567-696E-7300-0000-000000000000}" for "plugins"</returns>
  17. static public String GenerateGuid(String name)
  18. {
  19. byte[] buf = Encoding.UTF8.GetBytes(name);
  20. byte[] guid = new byte[16];
  21. if (buf.Length < 16)
  22. {
  23. Array.Copy(buf, guid, buf.Length);
  24. }
  25. else
  26. {
  27. using (SHA1 sha1 = SHA1.Create())
  28. {
  29. byte[] hash = sha1.ComputeHash(buf);
  30. // Hash is 20 bytes, but we need 16. We loose some of "uniqueness", but I doubt it will be fatal
  31. Array.Copy(hash, guid, 16);
  32. }
  33. }
  34.  
  35. // Don't use Guid constructor, it tends to swap bytes. We want to preserve original string as hex dump.
  36. String guidS = "{" + String.Format("{0:X2}{1:X2}{2:X2}{3:X2}-{4:X2}{5:X2}-{6:X2}{7:X2}-{8:X2}{9:X2}-{10:X2}{11:X2}{12:X2}{13:X2}{14:X2}{15:X2}",
  37. guid[0], guid[1], guid[2], guid[3], guid[4], guid[5], guid[6], guid[7], guid[8], guid[9], guid[10], guid[11], guid[12], guid[13], guid[14], guid[15]) + "}";
  38.  
  39. return guidS;
  40. }
Add Comment
Please, Sign In to add comment