using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
string input = "password";
// Generate SHA-256 hash without salt
string hashWithoutSalt = ComputeSha256Hash(input);
Console.WriteLine($"SHA-256 Hash (No Salt): {hashWithoutSalt}");
// Generate salt
byte[] salt = GenerateSalt(32); // 32 bytes = 256 bits
Console.WriteLine($"Generated Salt (Base64): {Convert.ToBase64String(salt)}");
// Generate SHA-256 hash with salt
string hashWithSalt = ComputeSha256HashWithSalt(input, salt);
Console.WriteLine($"SHA-256 Hash (With Salt): {hashWithSalt}");
}
// SHA-256 hash without salt
static string ComputeSha256Hash(string rawData)
{
using SHA256 sha256Hash = SHA256.Create();
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
return Convert.ToHexString(bytes);
}
// SHA-256 hash with salt
static string ComputeSha256HashWithSalt(string rawData, byte[] salt)
{
using SHA256 sha256Hash = SHA256.Create();
byte[] combined = Combine(Encoding.UTF8.GetBytes(rawData), salt);
byte[] hashBytes = sha256Hash.ComputeHash(combined);
return Convert.ToHexString(hashBytes);
}
// Generate a cryptographically secure salt
static byte[] GenerateSalt(int size)
{
byte[] salt = new byte[size];
using RandomNumberGenerator rng = RandomNumberGenerator.Create();
rng.GetBytes(salt);
return salt;
}
// Combine byte arrays
static byte[] Combine(byte[] first, byte[] second)
{
byte[] combined = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, combined, 0, first.Length);
Buffer.BlockCopy(second, 0, combined, first.Length, second.Length);
return combined;
}
}