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 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. SHA1 sha1 = new SHA1Managed();
  29. // gen salt2 hash
  30. byte[] dataSalt2 = Encoding.UTF8.GetBytes(salt2);
  31. byte[] salt2Bytes = hash.ComputeHash(dataSalt2);
  32. string salt2Str = string.Empty;
  33. foreach (byte x in salt2Bytes)
  34. {
  35. salt2Str += String.Format("{0:x2}", x);
  36. }
  37. string dataStr = salt1 + value + salt2Str;
  38. byte[] dataStrBytes = Encoding.UTF8.GetBytes(dataStr);
  39. byte[] shaBytes = sha1.ComputeHash(dataStrBytes);
  40. string sha1Str = string.Empty;
  41. foreach (byte x in shaBytes)
  42. {
  43. sha1Str += String.Format("{0:x2}", x);
  44. }
  45. byte[] sha1Bytes = Encoding.UTF8.GetBytes(sha1Str);
  46. byte[] valueBytes = hash.ComputeHash(sha1Bytes);
  47. string hashString = string.Empty;
  48. foreach (byte x in valueBytes)
  49. {
  50. hashString += String.Format("{0:x2}", x);
  51. }
  52. return hashString;
  53. }
  54. public static System.Security.Cryptography.SHA256 CreateHashAlgorithm()
  55. {
  56. if (CryptoConfig.AllowOnlyFipsAlgorithms)
  57. {
  58. return new SHA256CryptoServiceProvider();
  59. }
  60. return new SHA256Managed();
  61. }
  62. }
  63. }