using System; using System.IO; using System.Security.Cryptography; using System.Text; using Infrastructure.Extensions; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; namespace Infrastructure.Security { public class EncryptionService : IEncryptionService { private readonly string _key; private readonly string _iv; public EncryptionService(IConfiguration configuration) { this._key = configuration.GetSection("security").GetValue("key"); this._iv = configuration.GetSection("security").GetValue("iv"); } public string CreatePasswordHash(string password, string saltkey) { var saltAndPassword = String.Concat(password, saltkey); var algorithm = SHA1.Create(); var bytes = algorithm.ComputeHash(Encoding.UTF8.GetBytes(saltAndPassword)); var result = string.Empty; var builder = new StringBuilder(); builder.Append(result); foreach (var item in bytes) { builder.Append($"{item:x2}"); } result = builder.ToString(); return result; } public string CreateSalt() { var code = string.Empty; var builder = new StringBuilder(); builder.Append(code); for (int i = 0; i < 6; i++) { var random = new byte[1]; RandomNumberGenerator.Create().GetBytes(random); builder.Append(new Random(Convert.ToInt32(random[0])).Next(0, 9)); } code = builder.ToString(); return code; } public string EncryptObject(object obj) { var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj)); var key = Encoding.UTF8.GetBytes(this._key); var iv = Encoding.UTF8.GetBytes(this._iv); using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, TripleDES.Create().CreateEncryptor(key, iv), CryptoStreamMode.Write)) { cs.Write(data, 0, data.Length); cs.FlushFinalBlock(); } return ms.ToArray().BytesToHex(); } } public T DecryptObject(string value) { var data = value.HexToBytes(); var key = Encoding.UTF8.GetBytes(this._key); var iv = Encoding.UTF8.GetBytes(this._iv); using (var ms = new MemoryStream(data)) { using (var cs = new CryptoStream(ms, TripleDES.Create().CreateDecryptor(key, iv), CryptoStreamMode.Read)) { using (var sr = new StreamReader(cs, Encoding.UTF8)) { return JsonConvert.DeserializeObject(sr.ReadToEnd()); } } } } } }