using MAX.Models; using Microsoft.Extensions.Logging; using System; using System.IO; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace MAX { public static class Utils { public static byte[] Transform(ICryptoTransform transform, byte[] input) { using (var memoryStream = new MemoryStream()) using (var cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write)) { cryptoStream.Write(input, 0, input.Length); cryptoStream.FlushFinalBlock(); return memoryStream.ToArray(); } } public static string TripleDESDecrypt(string cipherText, TripleDES des) { using (var decryptor = des.CreateDecryptor(des.Key, des.IV)) { return Encoding.UTF8.GetString(Transform(decryptor, Convert.FromBase64String(cipherText))); } } public static string TripleDESDecrypt(string cipherText, byte[] key) { using (var des = TripleDES.Create()) { des.Key = key; des.IV = new byte[8]; return TripleDESDecrypt(cipherText, des); } } public static string TripleDESEncrypt(string plainText, TripleDES des) { using (var encryptor = des.CreateEncryptor(des.Key, des.IV)) { return Convert.ToBase64String(Transform(encryptor, Encoding.UTF8.GetBytes(plainText))); } } public static string TripleDESEncrypt(string plainText, byte[] key) { using (var des = TripleDES.Create()) { des.Key = key; des.IV = new byte[8]; return TripleDESEncrypt(plainText, des); } } public static async Task AuthenticateUserAsync(ClientFactory clientFactory, ILogger logger, int userId, string username, int vendorId, string serialNumber, string password) { using (var client = clientFactory.GetClient(logger, vendorId, serialNumber, userId, username, password)) { var user = await client.ConnectAsync().ConfigureAwait(false); if (user != null) { user.Account = await client.GetAccountAsync().ConfigureAwait(false); } return user; } } public static async Task GetProductCatalogueAsync( ClientFactory clientFactory, ILogger logger, LoginCredentials credentials) { using (var client = clientFactory.GetClient(logger, credentials)) { var user = await client.ConnectAsync().ConfigureAwait(false); if (user == null) { throw new Exception(string.Format("Invalid login credentials for {0}", credentials.ToString())); } return await client.GetProductCatalogueAsync(credentials.User.Account).ConfigureAwait(false); } } public static async Task PlaceOrderAsync( ClientFactory clientFactory, ILogger logger, LoginCredentials credentials, Product product, int quantity, string customerReference, Guid? orderGuid, byte[] key) { using (var client = clientFactory.GetClient(logger, credentials)) { var user = await client.ConnectAsync().ConfigureAwait(false); if (user == null) { throw new Exception(string.Format("Invalid login credentials for {0}", credentials.ToString())); } return await client.PlaceOrderAsync(credentials.User.AccountId, product, quantity, customerReference, orderGuid, key).ConfigureAwait(false); } } } }