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.3KB

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