IT/ASP.NET

[C#] Compute SHA256 Hash with Salt

GeunChoi 2021. 11. 1. 17:52
728x90
public static string SHA256Hash(string text, string salt = "salt")
{
  HashAlgorithm algorithm = new SHA256Managed();

  byte[] textBytes = Encoding.UTF8.GetBytes(text);
  byte[] saltBytes = Encoding.UTF8.GetBytes(salt);

  //Combine salt and input text
  List<byte> listByte = new List<byte>();
  listByte.AddRange(textBytes);
  listByte.AddRange(saltBytes);

  byte[] hashedBytes = algorithm.ComputeHash(listByte.ToArray());
  StringBuilder strBuilder = new StringBuilder();
  foreach(byte b in hashedBytes)
  {
  strBuilder.AppendFormat("{0:x2}", b);
  }

  return strBuilder.ToString();
}