Skip to content

Instantly share code, notes, and snippets.

@PaulNichols
Last active June 16, 2017 02:17
Show Gist options
  • Save PaulNichols/4236bdeea735f1ce6887e957359346f2 to your computer and use it in GitHub Desktop.
Save PaulNichols/4236bdeea735f1ce6887e957359346f2 to your computer and use it in GitHub Desktop.
Cryptography - Hash
using System;
using System.Security.Cryptography;
namespace CryptographyInDotNet
{
public class Hash
{
public static byte[] GenerateSalt()
{
const int saltLength = 32;
using (var randomNumberGenerator = new RNGCryptoServiceProvider())
{
var randomNumber = new byte[saltLength];
randomNumberGenerator.GetBytes(randomNumber);
return randomNumber;
}
}
private static byte[] Combine(byte[] first, byte[] second)
{
var ret = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, ret, 0, first.Length);
Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
return ret;
}
public static byte[] HashPasswordWithSalt(byte[] toBeHashed, byte[] salt)
{
using (var sha256 = SHA256.Create())
{
return sha256.ComputeHash(Combine(toBeHashed, salt));
}
}
}
}
using System;
using System.Text;
namespace CryptographyInDotNet
{
class Program
{
static void Main()
{
const string password = "V3ryC0mpl3xP455w0rd";
byte[] salt = Hash.GenerateSalt();
Console.WriteLine("Hash Password with Salt Demonstration in .NET");
Console.WriteLine("---------------------------------------------");
Console.WriteLine();
Console.WriteLine("Password : " + password);
Console.WriteLine("Salt = " + Convert.ToBase64String(salt));
Console.WriteLine();
var hashedPassword1 = Hash.HashPasswordWithSalt(
Encoding.UTF8.GetBytes(password),
salt);
Console.WriteLine();
Console.WriteLine("Hashed Password = " + Convert.ToBase64String(hashedPassword1));
Console.WriteLine();
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment