GuidGenerator.cs 1.0 KB

12345678910111213141516171819202122232425262728293031
  1. using System;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. namespace TeamAAS
  5. {
  6. /// <summary>
  7. /// GUID 工具。根据字符串生成确定性 GUID(同一输入永远得到同一 GUID),
  8. /// 供插件 ID、类型 Key 等场景跨项目复用。
  9. /// </summary>
  10. public static class GuidGenerator
  11. {
  12. /// <summary>
  13. /// 根据传入值生成确定性 GUID
  14. /// </summary>
  15. public static Guid GenerateGuidFromValue(string value)
  16. {
  17. if (string.IsNullOrEmpty(value))
  18. throw new ArgumentException("值不能为空", nameof(value));
  19. // 使用 SHA1 哈希(20 字节),取前 16 字节构建 GUID
  20. using (var sha1 = SHA1.Create())
  21. {
  22. byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(value));
  23. byte[] guidBytes = new byte[16];
  24. Array.Copy(hash, guidBytes, 16); // 截取前 16 字节
  25. return new Guid(guidBytes);
  26. }
  27. }
  28. }
  29. }