using System.ComponentModel;
using System.Security.Cryptography;
public static void Main()
var passwordToCheck = "monMotDePasse2020";
var passwordFormatInDb = PasswordFormat.Hashed;
var passwordInDb = "48DD9F3C18A5A37FA050CBA645701B2ED228DF3A";
var saltKeyInDb = "DUAGmGc=";
var customerService = new CustomerService();
var isValid = customerService.ValidatePassword(passwordToCheck, passwordInDb, passwordFormatInDb, saltKeyInDb);
Console.WriteLine("Password is valid " + isValid);
public enum PasswordFormat
public class CustomerService
private static EncryptionService _encryptionService = new EncryptionService();
private const string HashedPasswordFormat = "SHA1";
public bool ValidatePassword(string passwordToCheck, string passwordInDb, PasswordFormat passwordFormatInDb, string saltKeyInDb = null)
switch (passwordFormatInDb)
case PasswordFormat.Clear:
return passwordInDb == passwordToCheck;
case PasswordFormat.Encrypted:
return passwordInDb == _encryptionService.EncryptText(passwordToCheck);
case PasswordFormat.Hashed:
return passwordInDb == _encryptionService.CreatePasswordHash(passwordToCheck, saltKeyInDb, HashedPasswordFormat);
throw new InvalidEnumArgumentException("PasswordFormat must be one of Clear = 0 or Hashed = 1 or Encrypted = 2");
public class EncryptionService
private const string ENCRYPTION_KEY = "8410894616317067";
public virtual string CreatePasswordHash(string password, string saltkey, string passwordFormat = "SHA1")
return CreateHash(Encoding.UTF8.GetBytes(String.Concat(password, saltkey)), passwordFormat);
public virtual string CreateHash(byte[] data, string hashAlgorithm = "SHA1")
if (String.IsNullOrEmpty(hashAlgorithm))
var algorithm = HashAlgorithm.Create(hashAlgorithm);
throw new ArgumentException("Unrecognized hash name");
var hashByteArray = algorithm.ComputeHash(data);
return BitConverter.ToString(hashByteArray).Replace("-", "");
public virtual string EncryptText(string plainText, string encryptionPrivateKey = "")
if (string.IsNullOrEmpty(plainText))
if (String.IsNullOrEmpty(encryptionPrivateKey))
encryptionPrivateKey = ENCRYPTION_KEY;
var tDESalg = new TripleDESCryptoServiceProvider();
tDESalg.Key = Encoding.ASCII.GetBytes(encryptionPrivateKey.Substring(0, 16));
tDESalg.IV = Encoding.ASCII.GetBytes(encryptionPrivateKey.Substring(8, 8));
byte[] encryptedBinary = EncryptTextToMemory(plainText, tDESalg.Key, tDESalg.IV);
return Convert.ToBase64String(encryptedBinary);
private byte[] EncryptTextToMemory(string data, byte[] key, byte[] iv)
using (var ms = new MemoryStream())
using (var cs = new CryptoStream(ms, new TripleDESCryptoServiceProvider().CreateEncryptor(key, iv), CryptoStreamMode.Write))
byte[] toEncrypt = Encoding.Unicode.GetBytes(data);
cs.Write(toEncrypt, 0, toEncrypt.Length);
public virtual string CreateSaltKey(int size)
var rng = new RNGCryptoServiceProvider();
var buff = new byte[size];
return Convert.ToBase64String(buff);