UserHelper.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. namespace GreenTree.Maschinenbestellungen.Core.Helper
  6. {
  7. public class UserHelper : IUserHelper
  8. {
  9. /// <summary>
  10. /// Generates a MD5 hash from a string
  11. /// </summary>
  12. /// <param name="str">The string to encrypt.</param>
  13. /// <param name="lowerCase">Return hashed string in lower case.</param>
  14. public string HashString(string str, bool lowerCase)
  15. {
  16. if (String.IsNullOrEmpty(str))
  17. throw new ArgumentNullException("str", "An empty string cannot be encrypted.");
  18. // Byte array representation of that string
  19. var encodedStr = new UTF8Encoding().GetBytes(str);
  20. // Need MD5 to calculate the hash
  21. var hash = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedStr);
  22. // String representation (similar to UNIX format)
  23. var hashedStr = BitConverter.ToString(hash)
  24. .Replace("-", string.Empty)
  25. .ToLower();
  26. return lowerCase
  27. ? hashedStr.ToLower()
  28. : hashedStr;
  29. }
  30. }
  31. }