Skip to content

Instantly share code, notes, and snippets.

@VenenJean
Created November 12, 2023 14:31
Show Gist options
  • Save VenenJean/29d998710937a534c06c471212378672 to your computer and use it in GitHub Desktop.
Save VenenJean/29d998710937a534c06c471212378672 to your computer and use it in GitHub Desktop.
Hashing with SHA512 in C# (Salt + Pepper).
using System;
using System.Security.Cryptography;
using System.Text;
public class Hasher {
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
public string CreateHash(string input, byte[] salt, string pepper) {
byte[] saltBytes;
byte[] pepperBytes = Encoding.UTF8.GetBytes(pepper);
if (salt != Array.Empty<byte>()) {
saltBytes = salt;
} else {
int saltLength = 16;
saltBytes = new byte[saltLength];
Rng.GetNonZeroBytes(saltBytes);
Rng.Dispose();
}
byte[] inputData = Encoding.UTF8.GetBytes(input);
byte[] inputDataAndSalt = new byte[input.Length + saltBytes.Length];
byte[] inputDataAndSaltAndPepper = new byte[input.Length + saltBytes.Length + pepperBytes.Length];
byte[] hashValue = Array.Empty<byte>();
HMACSHA512 sha512 = new();
hashValue = sha512.ComputeHash(inputDataAndSaltAndPepper);
sha512.Dispose();
byte[] result = new byte[hashValue.Length + saltBytes.Length];
for (var i = 0; i < hashValue.Length; i++) {
result[i] = hashValue[i];
}
for (var i = 0; i < saltBytes.Length; i++) {
result[hashValue.Length + i] = saltBytes[i];
}
return Convert.ToBase64String(result);
}
public bool ConfirmHash(string input, string confirmHashValue, string pepper) {
byte[] confirmHashBytes = Convert.FromBase64String(confirmHashValue);
var hashSize = 64;
byte[] saltBytes = new byte[confirmHashBytes.Length - hashSize];
for (var i = 0; i < saltBytes.Length; i++) {
saltBytes[i] = confirmHashBytes[hashSize + 1];
}
string controlRehashValue = CreateHash(input, Array.Empty<byte>(), pepper);
return confirmHashValue == controlRehashValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment