using Common.Model; using Common.Model.Config; using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Mail; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; namespace Common.Helper { public static class Utilities { private static readonly Random Random = new Random(); private static readonly string MsisdnPrefix = ApplicationConfig.ReadWebConfig("MsisdnPrefix"); private static readonly string MsisdnLengthSetting = ApplicationConfig.ReadWebConfig("MsisdnLength"); private static EncryptionParameters _encryptionParams; private static JsonResponse response = new JsonResponse(); private static List lstSupportType { get; set; } private static List lstTransferType { get; set; } private static List lstActionType { get; set; } //private static List lstScheduleType { get; set; } /// /// Private method to initialize encryption parameters /// private static void InitializeEncryptionParameters() { _encryptionParams = new EncryptionParameters() { PassPhrase = ApplicationConfig.ReadWebConfig("symmetricKey"), HashAlgorithm = "SHA1", SaltValue = "sw!ftT3ch", PasswordIterations = 2, InitVector = "@1B2c3D4e5F6g7H8", KeySize = 256 }; } /// /// Encrypt string /// /// private static string Encrypt(EncryptionParameters encrypt) { byte[] initVectorBytes = Encoding.ASCII.GetBytes(encrypt.InitVector); byte[] saltValueBytes = Encoding.ASCII.GetBytes(encrypt.SaltValue); // Convert our plaintext into a byte array. byte[] plainTextBytes = Encoding.UTF8.GetBytes(encrypt.PlainText); PasswordDeriveBytes password = new PasswordDeriveBytes ( encrypt.PassPhrase, saltValueBytes, encrypt.HashAlgorithm, encrypt.PasswordIterations ); byte[] keyBytes = password.GetBytes(encrypt.KeySize / 8); // Create uninitialized Rijndael encryption object. RijndaelManaged symmetricKey = new RijndaelManaged(); symmetricKey.Mode = CipherMode.CBC; ICryptoTransform encryptor = symmetricKey.CreateEncryptor ( keyBytes, initVectorBytes ); // Define memory stream which will be used to hold encrypted data. MemoryStream memoryStream = new MemoryStream(); // Define cryptographic stream (always use Write mode for encryption). CryptoStream cryptoStream = new CryptoStream ( memoryStream, encryptor, CryptoStreamMode.Write ); // Start encrypting. cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); // Finish encrypting. cryptoStream.FlushFinalBlock(); // Convert our encrypted data from a memory stream into a byte array. byte[] cipherTextBytes = memoryStream.ToArray(); // Close both streams. memoryStream.Close(); cryptoStream.Close(); // Convert encrypted data into a base64-encoded string. string cipherText = Convert.ToBase64String(cipherTextBytes); // Return encrypted string. return cipherText; } /// /// Generate random 5 digit OTP /// /// public static string GenerateOTP() { string[] strChar = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; string otpChar = strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)]; return otpChar; } /// /// Decrypt string /// /// private static string Decrypt(EncryptionParameters decrypt) { byte[] initVectorBytes = Encoding.ASCII.GetBytes(decrypt.InitVector); byte[] saltValueBytes = Encoding.ASCII.GetBytes(decrypt.SaltValue); // Convert our ciphertext into a byte array. byte[] cipherTextBytes = Convert.FromBase64String(decrypt.CipherText); PasswordDeriveBytes password = new PasswordDeriveBytes ( decrypt.PassPhrase, saltValueBytes, decrypt.HashAlgorithm, decrypt.PasswordIterations ); // Use the password to generate pseudo-random bytes for the encryption key. Specify the // size of the key in bytes (instead of bits). byte[] keyBytes = password.GetBytes(decrypt.KeySize / 8); // Create uninitialized Rijndael encryption object. RijndaelManaged symmetricKey = new RijndaelManaged(); // It is reasonable to set encryption mode to Cipher Block Chaining symmetricKey.Mode = CipherMode.CBC; ICryptoTransform decryptor = symmetricKey.CreateDecryptor ( keyBytes, initVectorBytes ); // Define memory stream which will be used to hold encrypted data. MemoryStream memoryStream = new MemoryStream(cipherTextBytes); // Define cryptographic stream (always use Read mode for encryption). CryptoStream cryptoStream = new CryptoStream ( memoryStream, decryptor, CryptoStreamMode.Read ); byte[] plainTextBytes = new byte[cipherTextBytes.Length]; // Start decrypting. int decryptedByteCount = cryptoStream.Read ( plainTextBytes, 0, plainTextBytes.Length ); // Close both streams. memoryStream.Close(); cryptoStream.Close(); // Convert decrypted data into a string. string plainText = Encoding.UTF8.GetString ( plainTextBytes, 0, decryptedByteCount ); // Return decrypted string. return plainText; } public static string DecryptData(string key, string encrypedData) { if (string.IsNullOrEmpty(encrypedData)) { return ""; } string decData = null; byte[][] keys = GetHashKeys(key); try { decData = DecryptStringFromBytes_Aes(encrypedData, keys[0], keys[1]); } catch (CryptographicException) { } catch (ArgumentNullException) { } return decData; } private static byte[][] GetHashKeys(string key) { byte[][] result = new byte[2][]; Encoding enc = Encoding.UTF8; SHA256 sha2 = new SHA256CryptoServiceProvider(); byte[] rawKey = enc.GetBytes(key); byte[] rawIV = enc.GetBytes(key); byte[] hashKey = sha2.ComputeHash(rawKey); byte[] hashIV = sha2.ComputeHash(rawIV); Array.Resize(ref hashIV, 16); result[0] = hashKey; result[1] = hashIV; return result; } private static string DecryptStringFromBytes_Aes(string cipherTextString, byte[] Key, byte[] IV) { byte[] cipherText = Convert.FromBase64String(cipherTextString); //final byte[] plainTextBytes = (orignalText) if (cipherText == null || cipherText.Length <= 0) throw new ArgumentNullException("cipherText"); if (Key == null || Key.Length <= 0) throw new ArgumentNullException("Key"); if (IV == null || IV.Length <= 0) throw new ArgumentNullException("IV"); string plaintext = null; using (Aes aesAlg = Aes.Create()) { aesAlg.Mode = CipherMode.CBC; aesAlg.KeySize = 256; aesAlg.BlockSize = 128; aesAlg.Padding = PaddingMode.PKCS7; aesAlg.Key = Key; aesAlg.IV = new byte[16]; ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msDecrypt = new MemoryStream(cipherText)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { plaintext = srDecrypt.ReadToEnd(); } } } } return plaintext; } /// /// Generate Random 4 digit Pin /// /// public static string GenerateRandomPin() { string[] strChar = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; string otpChar = strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)]; return otpChar; } /// /// Encrypt plain text to cipher text. /// /// /// public static string EncryptString(string plainText) { InitializeEncryptionParameters(); EncryptionParameters _encrypt = new EncryptionParameters() { PlainText = plainText, PassPhrase = _encryptionParams.PassPhrase, HashAlgorithm = _encryptionParams.HashAlgorithm, SaltValue = _encryptionParams.SaltValue, PasswordIterations = _encryptionParams.PasswordIterations, InitVector = _encryptionParams.InitVector, KeySize = _encryptionParams.KeySize }; var s = Utilities.Encrypt(_encrypt); return s; } /// /// Decrypt encrypted/cipher text to plain text. /// /// /// public static string DecryptString(string cipherText) { try { InitializeEncryptionParameters(); EncryptionParameters _decrypt = new EncryptionParameters() { CipherText = cipherText, PassPhrase = _encryptionParams.PassPhrase, HashAlgorithm = _encryptionParams.HashAlgorithm, SaltValue = _encryptionParams.SaltValue, PasswordIterations = _encryptionParams.PasswordIterations, InitVector = _encryptionParams.InitVector, KeySize = _encryptionParams.KeySize }; return Utilities.Decrypt(_decrypt); } catch (Exception ex) { return ""; } } /// /// Check for email validity /// /// /// public static bool IsValidEmail(this string email) { return Regex.IsMatch(email ?? "", ApplicationConfig.ReadWebConfig("regex"), RegexOptions.IgnoreCase); } /// /// Check for residence card number /// /// /// public static bool IsValidNumber(this string residenceCardNo) { return Regex.IsMatch(residenceCardNo ?? "", ApplicationConfig.ReadWebConfig("regexResidenceCard"), RegexOptions.IgnoreCase); } public static bool IsValidMobileNumber(this string mobile) { return Regex.IsMatch(mobile ?? "", ApplicationConfig.ReadWebConfig("regexMobile"), RegexOptions.IgnoreCase); } public static bool IsValidDrivingNumber(this string drivingNo) { return Regex.IsMatch(drivingNo ?? "", ApplicationConfig.ReadWebConfig("regexDrivingLiscence"), RegexOptions.IgnoreCase); } public static bool IsCheckAdditionalId() { var additionalid = ApplicationConfig.ReadWebConfig("CheckAdditinalID"); if (additionalid != null && additionalid.Equals("Y")) return true; else return false; } /// /// Check for 4 digit pin number /// /// /// public static bool IsValidPin(this string pin) { if (!string.IsNullOrEmpty(pin)) { int iPin; if (pin.Length != 4) { return false; } return int.TryParse(pin, out iPin); } else { return false; } } /// /// Check Wether the Mobile Number is Valid or not /// /// /// public static bool IsValidMsisdn(this string msisdn) { int minPrefix = 2; int maxPrefix = 4; int chkFlag = 0; if (!string.IsNullOrEmpty(msisdn)) { long iMsisdn; var splitMsisdnLength = MsisdnLengthSetting.Split('|').ToList(); if (splitMsisdnLength.Contains(msisdn.Length.ToString())) { var splitPrefix = MsisdnPrefix.Split('|').ToList(); for (int i = minPrefix; i <= maxPrefix; i++) { if (splitPrefix.Contains(msisdn.Substring(0, i))) //checking prefix { chkFlag = 1; break; } else { continue; } } if (chkFlag == 0) { return false; } } else { return false; } return long.TryParse(msisdn, out iMsisdn); } else { return false; } } public static bool IsValidARCFormat(string idType, string vin) { if (idType == ApplicationConfig.ReadWebConfig("kycVerificationIdType") || idType == ApplicationConfig.ReadWebConfig("kycNationalIdType")) { var number = vin.Split('-'); if (number.Length != 2) { return false; } else if (number[0].Length != 6 || number[1].Length != 7) { return false; } else { return true; } } else { return true; } } /// /// Generate Random Password /// /// /// public static string GenerateRandomPassword(int length) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return new string(Enumerable.Repeat(chars, length) .Select(s => s[Random.Next(s.Length)]).ToArray()); } public static string GetTimestamp(DateTime value) { return value.ToString("yyyyMMddHHmmssffff"); } /// /// Used to send email /// /// /// public static JsonResponse SendEmail(SendEmailParameters emailParameters) { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient(); try { SmtpServer.Host = ApplicationConfig.ReadWebConfig("smtp"); SmtpServer.Port = Convert.ToInt16(ApplicationConfig.ReadWebConfig("port")); SmtpServer.Credentials = new System.Net.NetworkCredential(ApplicationConfig.ReadWebConfig("mailFrom"), ApplicationConfig.ReadWebConfig("emailPwd")); SmtpServer.EnableSsl = Convert.ToBoolean(ApplicationConfig.ReadWebConfig("enableSSL")); mail.From = new MailAddress(ApplicationConfig.ReadWebConfig("mailFrom"), ApplicationConfig.ReadWebConfig("mailSender")); mail.To.Add(emailParameters.ToEmails); if (!string.IsNullOrEmpty(emailParameters.CcEmails)) mail.CC.Add(emailParameters.CcEmails); if (!string.IsNullOrEmpty(emailParameters.BccEmails)) mail.Bcc.Add(emailParameters.BccEmails); mail.Subject = emailParameters.MsgSubject; mail.IsBodyHtml = true; mail.Body = emailParameters.MsgBody; SmtpServer.Send(mail); response.SetResponseMessage(HttpStatusCode.OK, "Message sent successfully"); } catch (SmtpFailedRecipientsException ex) { for (int i = 0; i < ex.InnerExceptions.Length; i++) { SmtpStatusCode status = ex.InnerExceptions[i].StatusCode; if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable) { // Console.WriteLine("Delivery failed - retrying in 5 seconds."); System.Threading.Thread.Sleep(5000); SmtpServer.Send(mail); response.SetResponseMessage(HttpStatusCode.OK, "Message sent successfully"); } else { response.SetResponseMessage(HttpStatusCode.BadRequest, ex.InnerExceptions[i].FailedRecipient); // Console.WriteLine("Failed to deliver message to {0}", ex.InnerExceptions[i].FailedRecipient); //throw ex; //smtpMail.Status = "N"; //GetStatic.EmailNotificationLog(smtpMail); } } } catch (Exception ex) { response.SetResponseMessage(HttpStatusCode.BadRequest, ex.Message); } return response; } /// /// To check the properties of a class for Null/Empty values /// /// The instance of the class /// Result of the evaluation public static bool IsAnyNullOrEmpty(object obj) { //Step 1: Set the count variable to check for the count of 2. int count = 0; try { //Step 2: Check if the incoming object has values or not. if (obj != null) { //Step 3: Iterate over the properties and check for null values based on the type. foreach (PropertyInfo pi in obj.GetType().GetProperties()) { if (count >= 2) { return true; } dynamic value; if (pi.PropertyType == typeof(string)) { value = (string)pi.GetValue(obj); if (!string.IsNullOrEmpty(value)) { count++; } } else if (pi.PropertyType == typeof(int)) { value = (int)pi.GetValue(obj); if (value > 0) { count++; } } else if (pi.PropertyType == typeof(List)) { value = (List)pi.GetValue(obj); if (value != null) { if (value.Count > 0) { count++; } } } else if (pi.PropertyType == typeof(bool)) { value = pi.GetValue(obj); if (value != null) { count++; } } } //Step 4: Check if the count variable is >2 that means there is atleast one parameter passed in the body if (count >= 2) { return true; } } } catch (Exception ex) { throw ex; } return false; } public static string ConvertToUnixTimestamp(string str) { try { DateTime date = Convert.ToDateTime(str); DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0); TimeSpan diff = date - origin; return Math.Floor(diff.TotalSeconds).ToString(); } catch (Exception) { return ""; } } public static bool ConvertToGlobalFormat(string param) { try { if (string.IsNullOrEmpty(param)) { return true; } DateTime dt; string[] formats = { "yyyy-MM-dd", "yyyy/MM/dd", "MM/dd/yyyy", "MM-dd-yyyy", "dd/MM/yyyy" }; if (DateTime.TryParseExact(param, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt)) { return true; } else { return false; } } catch (Exception ex) { return false; } } public static String ShowDecimal(String strVal) { if (strVal != "") return String.Format("{0:0,0.00}", double.Parse(strVal)); else return strVal; } public static bool IsSupportTypeValid(string str) { var lstSupportType = LoadSupportType(); return lstSupportType.Contains(str) ? true : false; } private static List LoadSupportType() { if (lstSupportType == null) { lstSupportType = new List(); lstSupportType.Add("feedback"); lstSupportType.Add("enquiry"); } return lstSupportType; } public static bool IsTransferTypeValid(string type) { var lstTransferType = LoadTransferType(); return lstTransferType.Contains(type) ? true : false; } private static List LoadTransferType() { if (lstTransferType == null) { lstTransferType = new List(); lstTransferType.Add("offer"); lstTransferType.Add("request"); } return lstTransferType; } public static bool IsActionTypeValid(string type) { var lstActionType = LoadActionType(); return lstActionType.Contains(type) ? true : false; } private static List LoadActionType() { if (lstActionType == null) { lstActionType = new List(); lstActionType.Add("accept"); lstActionType.Add("reject"); } return lstActionType; } //public static bool IsScheduleTypeValid(string type) //{ // var lstScheduleType = LoadScheduleType(); // return lstScheduleType.Contains(type) ? true : false; //} //private static List LoadScheduleType() //{ // if (lstScheduleType == null) // { // lstScheduleType = new List(); // lstScheduleType.Add("0"); // lstScheduleType.Add("1"); // } // return lstScheduleType; //} public static int GetOriginalLengthInBytes(string base64string) { if (string.IsNullOrEmpty(base64string)) { return 0; } var characterCount = base64string.Length; var paddingCount = base64string.Substring(characterCount - 2, 2) .Count(c => c == '='); return (3 * (characterCount / 4)) - paddingCount; } public static string[] SelectDistinct(this string[] array) { return array.Distinct().ToArray(); } public static string ReadWebConfig(string key, string defValue) { var Key = ConfigurationManager.AppSettings[key] ?? defValue; return Key; } public static bool CheckDateType(string date) { DateTime dt; string[] formats = { "yyyy-MM-dd" }; if (!DateTime.TryParseExact(date, formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) { return false; } else { return true; } } public static KYCConfigDto GetKYCSettings(KycRequest obj) { KYCConfigDto dt = new KYCConfigDto() { Config = new TrustDocConfig(), Options = new List() }; KYCConfig referenceMaps = new KYCConfig(); //string mappingPath = mappingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, obj.DeviceType.ToLower().Equals("android") ? "config\\KycConfig-uat.json" : ConfigurationManager.AppSettings["KycConfigFilePath"].ToString()); string mappingPath = mappingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["KycConfigFilePath"].ToString()); using (StreamReader reader = File.OpenText(mappingPath)) { var jsonS = reader.ReadToEnd(); referenceMaps = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonS); } if (!string.IsNullOrEmpty(obj.DeviceType)) { dt.Config = referenceMaps.Config.Where(x => x.DeviceType.ToLower().Equals(obj.DeviceType.ToLower())).SingleOrDefault(); } dt.Options = referenceMaps.Options; return dt; } public static List