paasword salt and hash c# code example
Example 1: c# sha512 salt
using RandomNumberGenerator;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace HashingAlgos
{
public class PasswordWithSaltHasher
{
public HashWithSaltResult HashWithSalt(string password, int saltLength, HashAlgorithm hashAlgo)
{
RNG rng = new RNG();
byte[] saltBytes = rng.GenerateRandomCryptographicBytes(saltLength);
byte[] passwordAsBytes = Encoding.UTF8.GetBytes(password);
List<byte> passwordWithSaltBytes = new List<byte>();
passwordWithSaltBytes.AddRange(passwordAsBytes);
passwordWithSaltBytes.AddRange(saltBytes);
byte[] digestBytes = hashAlgo.ComputeHash(passwordWithSaltBytes.ToArray());
return new HashWithSaltResult(Convert.ToBase64String(saltBytes), Convert.ToBase64String(digestBytes));
}
}
}
Example 2: c# sha512 salt
static byte[] GenerateSaltedHash(byte[] plainText, byte[] salt)
{
HashAlgorithm algorithm = new SHA256Managed();
byte[] plainTextWithSaltBytes =
new byte[plainText.Length + salt.Length];
for (int i = 0; i < plainText.Length; i++)
{
plainTextWithSaltBytes[i] = plainText[i];
}
for (int i = 0; i < salt.Length; i++)
{
plainTextWithSaltBytes[plainText.Length + i] = salt[i];
}
return algorithm.ComputeHash(plainTextWithSaltBytes);
}