The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SHA256.cs 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.IO;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. namespace Teknik.Utilities.Cryptography
  6. {
  7. public class SHA256
  8. {
  9. public static string Hash(string value)
  10. {
  11. byte[] valueBytes = Encoding.UTF8.GetBytes(value);
  12. return Hash(valueBytes);
  13. }
  14. public static string Hash(byte[] value)
  15. {
  16. HashAlgorithm hash = new SHA256CryptoServiceProvider();
  17. byte[] hashBytes = hash.ComputeHash(value);
  18. return Convert.ToBase64String(hashBytes);
  19. }
  20. public static byte[] Hash(Stream value)
  21. {
  22. HashAlgorithm hash = new SHA256CryptoServiceProvider();
  23. return hash.ComputeHash(value);
  24. }
  25. public static string Hash(string value, string salt1, string salt2)
  26. {
  27. SHA256Managed hash = new SHA256Managed();
  28. // gen salt2 hash
  29. byte[] dataSalt2 = Encoding.UTF8.GetBytes(salt2);
  30. byte[] salt2Bytes = hash.ComputeHash(dataSalt2);
  31. string salt2Str = string.Empty;
  32. foreach (byte x in salt2Bytes)
  33. {
  34. salt2Str += String.Format("{0:x2}", x);
  35. }
  36. string dataStr = salt1 + value + salt2Str;
  37. string sha1Str = SHA1.Hash(dataStr);
  38. byte[] sha1Bytes = Encoding.UTF8.GetBytes(sha1Str);
  39. byte[] valueBytes = hash.ComputeHash(sha1Bytes);
  40. string hashString = string.Empty;
  41. foreach (byte x in valueBytes)
  42. {
  43. hashString += String.Format("{0:x2}", x);
  44. }
  45. return hashString;
  46. }
  47. public static System.Security.Cryptography.SHA256 CreateHashAlgorithm()
  48. {
  49. if (CryptoConfig.AllowOnlyFipsAlgorithms)
  50. {
  51. return new SHA256CryptoServiceProvider();
  52. }
  53. return new SHA256Managed();
  54. }
  55. }
  56. }