using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace Tango.Core.Cryptography { /// /// Represents a hashing algorithm engine for one-way password encryption. /// /// public class BasicHashGenerator : IHashGenerator { /// /// Encrypts the specified text using the static salt key. /// /// The text. /// public string Encrypt(string text) { return Encrypt(text, "twine-solutions9"); } /// /// Encrypts the specified text using the specified salt. /// /// The text. /// The key. /// public string Encrypt(string text, string salt) { if (salt.Length < 16) { salt = salt.PadRight(16); } salt = salt.Substring(0, 16); byte[] saltBytes = Encoding.ASCII.GetBytes(salt); var pbkdf2 = new Rfc2898DeriveBytes(text, saltBytes, 10000); byte[] hash = pbkdf2.GetBytes(20); byte[] hashBytes = new byte[36]; Array.Copy(saltBytes, 0, hashBytes, 0, 16); Array.Copy(hash, 0, hashBytes, 16, 20); return Convert.ToBase64String(hashBytes); } /// /// Validates the specified text against the specified hash. /// /// The text. /// public bool Validate(string text, string hash) { byte[] hashBytes = Convert.FromBase64String(hash); byte[] salt = new byte[16]; Array.Copy(hashBytes, 0, salt, 0, 16); var pbkdf2 = new Rfc2898DeriveBytes(text, salt, 10000); byte[] h = pbkdf2.GetBytes(20); for (int i = 0; i < 20; i++) { if (hashBytes[i + 16] != h[i]) { return false; } } return true; } } }