public string CreateRegistrationVerificationEmail(UserMaster user, string token) { AesAlgorithm aesAlgorithm = new AesAlgorithm(); var key = string.Join(":", new string[] { DateTime.Now.Ticks.ToString(), user.UserId.ToString() }); var encrypt = aesAlgorithm.EncryptToBase64String(key); var linktoverify = $"{_appSettings.VerifyRegistrationUrl}?key={HttpUtility.UrlEncode(encrypt)}&hashtoken={HttpUtility.UrlEncode(token)}"; var stringtemplate = new StringBuilder(); stringtemplate.Append("Welcome"); stringtemplate.Append("<br/>"); stringtemplate.Append($"Dear {user.FirstName}{user.LastName}"); stringtemplate.Append("<br/>"); stringtemplate.Append("Thanks for joining Web Secure."); stringtemplate.Append("<br/>"); stringtemplate.Append("To activate your Web Secure account, please confirm your email address."); stringtemplate.Append("<br/>"); stringtemplate.Append("<a target='_blank' href=" + linktoverify + ">Confirm Email</a>"); stringtemplate.Append("<br/>"); stringtemplate.Append("Yours sincerely,"); stringtemplate.Append("<br/>"); stringtemplate.Append("Frapper"); stringtemplate.Append("<br/>"); return(stringtemplate.ToString()); }
public string SendVerificationEmail(RegisterViewModel registerViewModel, string token, long userid) { AesAlgorithm aesAlgorithm = new AesAlgorithm(); var key = string.Join(":", new string[] { DateTime.Now.Ticks.ToString(), userid.ToString() }); var encrypt = aesAlgorithm.EncryptToBase64String(key); var linktoverify = _appSettings.VerifyRegistrationUrl + "?key=" + HttpUtility.UrlEncode(encrypt) + "&hashtoken=" + HttpUtility.UrlEncode(token); var stringtemplate = new StringBuilder(); stringtemplate.Append("Welcome"); stringtemplate.Append("<br/>"); stringtemplate.Append("Dear " + registerViewModel.FullName); stringtemplate.Append("<br/>"); stringtemplate.Append("Thanks for joining Web Secure."); stringtemplate.Append("<br/>"); stringtemplate.Append("To activate your Web Secure account, please confirm your email address."); stringtemplate.Append("<br/>"); stringtemplate.Append("<a target='_blank' href=" + linktoverify + ">Confirm Email</a>"); stringtemplate.Append("<br/>"); stringtemplate.Append("Yours sincerely,"); stringtemplate.Append("<br/>"); stringtemplate.Append("Ticket's"); stringtemplate.Append("<br/>"); return(stringtemplate.ToString()); }
public ActionResult Create(CreateUserViewModel createUserViewModel) { try { if (ModelState.IsValid) { var isUser = _iUserMaster.CheckUsernameExists(createUserViewModel.UserName); if (isUser) { ModelState.AddModelError("", "Username already exists"); } AesAlgorithm aesAlgorithm = new AesAlgorithm(); var usermaster = AutoMapper.Mapper.Map <Usermaster>(createUserViewModel); usermaster.Status = true; usermaster.CreateDate = DateTime.Now; usermaster.UserId = 0; usermaster.CreatedBy = Convert.ToInt32(Session["UserID"]); var userId = _iUserMaster.AddUser(usermaster); if (userId != -1) { var passwordMaster = new PasswordMaster { CreateDate = DateTime.Now, UserId = userId, PasswordId = 0, Password = aesAlgorithm.EncryptString(createUserViewModel.Password) }; var passwordId = _iPassword.SavePassword(passwordMaster); if (passwordId != -1) { var savedAssignedRoles = new SavedAssignedRoles() { RoleId = createUserViewModel.RoleId, UserId = userId, AssignedRoleId = 0, Status = true, CreateDate = DateTime.Now }; _savedAssignedRoles.AddAssignedRoles(savedAssignedRoles); TempData["MessageCreateUsers"] = "User Created Successfully"; } } return(RedirectToAction("Create", "CreateUsers")); } else { return(View("Create", createUserViewModel)); } } catch { throw; } }
public ActionResult Create(CustomerViewModel customerViewModel) { try { if (ModelState.IsValid) { var isCustomer = _iCustomer.CheckCustomernameExists(customerViewModel.CustomerEmail); if (isCustomer) { ModelState.AddModelError("", "Customer already exists"); } AesAlgorithm aesAlgorithm = new AesAlgorithm(); var customer = AutoMapper.Mapper.Map <Customers>(customerViewModel); customer.Status = true; customer.CustomerID = 0; customer.CreatedBy = Convert.ToInt32(Session["UserID"]); var customerId = _iCustomer.AddCustomer(customer); if (customerId != -1) { var passwordMaster = new PasswordMaster { CreateDate = DateTime.Now, UserId = customerId, PasswordId = 0, Password = aesAlgorithm.EncryptString(customerViewModel.Password), UserEmail = customerViewModel.CustomerEmail }; var passwordId = _iPassword.SavePassword(passwordMaster); if (passwordId != -1) { var savedAssignedRoles = new SavedAssignedRoles() { RoleId = 3, UserId = customerId, AssignedRoleId = 0, Status = true, CreateDate = DateTime.Now }; _savedAssignedRoles.AddAssignedRoles(savedAssignedRoles); TempData["MessageCreateUsers"] = "User Created Successfully"; } } return(RedirectToAction("Index", "Customer")); } else { return(View("Create")); } } catch { throw; } }
public void Test_Decrypt_IsThrowingCryptographicExceptionForWrongData() { var aesAlgorithm = new AesAlgorithm(); Assert.Throws <CryptographicException>(() => aesAlgorithm.Decrypt(new byte[] { 12, 20, 25 }, new byte[] { 212, 29, 140, 217, 143, 0, 178, 4, 233, 128, 9, 152, 236, 248, 66, 126, 212, 29, 140, 217, 143, 0, 178, 4, 233, 128, 9, 152, 236, 248, 66, 126 }, new byte[] { 212, 29, 140, 217, 143, 0, 178, 4, 233, 128, 9, 152, 236, 248, 66, 126 })); }
public async Task SendVerificationEmailasync(string emailid, string name, string token, string sendingType, string userid) { try { AesAlgorithm aesAlgorithm = new AesAlgorithm(); var key = string.Join(":", new string[] { DateTime.Now.Ticks.ToString(), userid }); var encrypt = aesAlgorithm.EncryptToBase64String(key); var linktoverify = ConfigurationManager.AppSettings["VerifyRegistrationURL"] + "?key=" + HttpUtility.UrlEncode(encrypt) + "&hashtoken=" + HttpUtility.UrlEncode(token); if (emailid != null) { var generalsetting = GetGeneralSetting(); if (generalsetting != null) { if (generalsetting.EnableEmailFeature) { IProcessSettings processSettings = new ProcessSettingsConcrete(); var settingobject = processSettings.GetDefaultEmailSettings(); string from = generalsetting.Email; if (settingobject != null) { MailMessage message = new MailMessage(); SmtpClient smtpClient = new SmtpClient(); try { MailAddress fromAddress = new MailAddress(from); message.From = fromAddress; message.To.Add(emailid); message.Subject = "Welcome to Ticket's"; message.IsBodyHtml = true; message.Body = SendVerificationEmail(name, linktoverify); // We use mail as our smtp client smtpClient.Host = settingobject.Host; smtpClient.Port = Convert.ToInt32(settingobject.Port); smtpClient.EnableSsl = settingobject.SslProtocol == "Y" ? true : false; smtpClient.UseDefaultCredentials = true; smtpClient.Credentials = new System.Net.NetworkCredential(settingobject.Username, settingobject.Password); await smtpClient.SendMailAsync(message); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); } } } } } } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); } }
public static string[] SplitToken(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } AesAlgorithm aesAlgorithm = new AesAlgorithm(); var decryptkey = aesAlgorithm.DecryptFromBase64String(key); string[] parts = decryptkey.Split(new char[] { ':' }); return(parts); }
public void EncryptTest() { string cipherText = AesAlgorithm.Encrypt(m_sourceString); if (!String.IsNullOrWhiteSpace(cipherText)) { Assert.IsNotNull(cipherText); } else { Assert.Fail(); } }
/// <summary> /// Validates the masterkey by decrypting the given fortress and flushing the memory afterwards. /// </summary> /// <param name="fortressFullPath"></param> /// <param name="fortressName"></param> /// <param name="password"></param> internal void ValidateMasterKey(string fortressFullPath, string fortressName, string password) { try { Logger.log.Info($"Start validating the masterkey of fortress {fortressFullPath}..."); var aesHelper = new AesHelper(); // =========================================================== Unzip the fortress - Read salt var unzippedFortress = ZipHelper.UnzipSavedZip(fortressFullPath); using (unzippedFortress) { var entryOfSalt = fortressName + "/salt" + TermHelper.GetTextFileEnding(); var saltEntry = unzippedFortress.GetEntry(entryOfSalt); var saltBytes = new byte[32]; using (var stream = saltEntry.Open()) { saltBytes = ByteHelper.ReadBytesOfStream(stream); } Logger.log.Debug("Unzipped fortress - Salt bytes read."); // =========================================================== Create masterkey var hashedKey = aesHelper.CreateKey(password, 256, saltBytes); password = string.Empty; // Delete the password in plaintext from RAM var masterKey = new Masterkey(hashedKey); Logger.log.Debug("Masterkey created."); // =========================================================== Decrypt database var entryOfDatabase = fortressName + "/" + TermHelper.GetDatabaseTerm() + TermHelper.GetDatabaseEnding(); var databaseEntry = unzippedFortress.GetEntry(entryOfDatabase); var aesAlg = new AesAlgorithm(); using (var stream = databaseEntry.Open()) { var dbBytes = ByteHelper.ReadBytesOfStream(stream); var decryptedDb = aesAlg.Decrypt(dbBytes, masterKey.Value, saltBytes); Logger.log.Info($"Validated {TermHelper.GetDatabaseTerm()}"); decryptedDb = null; } } } catch (Exception ex) { ex.SetUserMessage(WellKnownExceptionMessages.DataExceptionMessage()); throw ex; } }
public void DecryptTest() { string cipherText = "jTIXGJHmu4AjzU2dG1mhz4lRVvC8gmi5udHfHO3sovA="; string decryptText = AesAlgorithm.Decrypt(cipherText); if (!String.IsNullOrWhiteSpace(decryptText)) { Assert.AreEqual(decryptText, m_sourceString); } else { Assert.Fail(); } }
public ActionResult Create(CustomerViewModel customerViewModel) { if (ModelState.IsValid) { Customer customerObject = db.Customer.Where(x => x.CustomerEmail == customerViewModel.CustomerEmail).FirstOrDefault(); if (customerObject == null) { ModelState.AddModelError("", "Customer already exists"); } AesAlgorithm aesAlgorithm = new AesAlgorithm(); var customer = AutoMapper.Mapper.Map <Customer>(customerViewModel); customer.Status = true; customer.CustomerId = 0; customer.CreatedBy = Convert.ToInt32(Session["UserID"]); db.Customer.Add(customer); db.SaveChanges(); int customerId = customer.CustomerId; var passwordMaster = new PasswordMaster { CreateDate = DateTime.Now, UserId = customerId, PasswordId = 0, Password = aesAlgorithm.EncryptString(customerViewModel.Password), UserEmail = customerViewModel.CustomerEmail }; var passwordId = _iPassword.SavePassword(passwordMaster); if (passwordId != -1) { var savedAssignedRoles = new SavedAssignedRoles() { RoleId = 3, UserId = customerId, AssignedRoleId = 0, Status = true, CreateDate = DateTime.Now, }; _savedAssignedRoles.AddAssignedRoles(savedAssignedRoles); TempData["MessageCreateUsers"] = "User Created Successfully"; } return(RedirectToAction("Index")); } else { return(View("Create")); } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { //Get the start page var startPage = _config.Value.GFCUrls.StartPage; //Get the controller var controller = (BaseController)filterContext.Controller; //Check the allowed CORS Domains var origin = GetOrigin(filterContext); //Get the allowed domains var allowedDomains = string.IsNullOrEmpty(_config.Value.AllowedCorsDomains) ? new string[] { } : _config.Value.AllowedCorsDomains.Split(','); //Check origin against allowed domains var isOriginAllowed = allowedDomains.Contains(origin.Host); //If origin is not allowed send user to error page if (!isOriginAllowed) { filterContext.Result = controller.GetCustomErrorCode(EnumStatusCode.CrossDomainOriginResourcesSharing, $"Cross Origin Resources Sharing - Invalid Domain - {origin.Host}"); } //Check the encrypted key in the form post var encKeyFromPost = filterContext.HttpContext.Request.Form[_gfcKeyName].FirstOrDefault(); var keyFromPost = AesAlgorithm.Decrypt(_corsConfig.Value.GFCKey, encKeyFromPost); // If no key or invalid key, send user to error page if (string.IsNullOrEmpty(keyFromPost) || _corsConfig.Value.GFCPassword != keyFromPost) { filterContext.Result = controller.GetCustomErrorCode(EnumStatusCode.CrossDomainOriginResourcesSharing, "Cross Origin Resources Sharing - Form Post key was invalid"); } //We've passed our checks, add the headers to the response filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", $"{origin.Scheme}://{origin.Host}"); filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept" }); filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "POST, GET, OPTIONS" }); // new[] { "GET, POST, PUT, DELETE, OPTIONS" } }
public ActionResult Register(UsermasterView usermaster) { try { if (ModelState.IsValid) { var autoUsermaster = AutoMapper.Mapper.Map <Usermaster>(usermaster); var isUser = _iUserMaster.CheckUsernameExists(usermaster.UserName); if (isUser) { ModelState.AddModelError("", "Username already exists"); } AesAlgorithm aesAlgorithm = new AesAlgorithm(); var userId = _iUserMaster.AddUser(autoUsermaster); if (userId != -1) { PasswordMaster passwordMaster = new PasswordMaster { CreateDate = DateTime.Now, UserId = userId, PasswordId = 0, Password = aesAlgorithm.EncryptString(usermaster.Password) }; var passwordId = _iPassword.SavePassword(passwordMaster); if (passwordId != -1) { TempData["MessageRegistration"] = "Registration Successful"; } } return(RedirectToAction("Register", "Registration")); } else { return(View("Register", usermaster)); } } catch { throw; } }
private void SucceedRequirementIfKeyPresentAndValid(AuthorizationHandlerContext context, KeyRequirement requirement) { if (context.Resource is AuthorizationFilterContext authorizationFilterContext) { if (!AllowCrossOrigin(authorizationFilterContext)) { _logger.LogError("Cross Domain Origin Resources Sharing Post Error Occured", EnumStatusCode.CrossDomainOriginResourcesSharing); context.Fail(); } //requested data using form-urlencoded var encryptedString = authorizationFilterContext.HttpContext.Request.Form[GFC_KEY_NAME].FirstOrDefault(); if (encryptedString != null && requirement.Keys[GFC_PASSWORD] == AesAlgorithm.Decrypt(requirement.Keys[GFC_KEY], encryptedString)) { context.Succeed(requirement); } } }
static void Main(string[] args) { //Guid key generated with base64encoded and uppercase combination var key = "A+W2nzdpbEe3UHrCBZU5Qw=="; //Console.WriteLine("Please enter a secret key for the symmetric algorithm."); //var key = Console.ReadLine(); Console.WriteLine("Please enter a string for encryption"); var str = Console.ReadLine(); var encryptedString = AesAlgorithm.Encrypt(key, str); Console.WriteLine($"encrypted string = {encryptedString}"); var decryptedString = AesAlgorithm.Decrypt(key, encryptedString); Console.WriteLine($"decrypted string = {decryptedString}"); Console.ReadKey(); }
public static void TestFileEncryption() { byte[] encryptedFile; //using (FileStream fs = new FileStream("C:\\Users\\Nutzer\\Desktop\\4484d5bb-658f-47f5-a1f0-ab738c120252.xml", FileMode.Open, FileAccess.ReadWrite, FileShare.Read)) //{ // XmlDocument testDoc = new XmlDocument(); // testDoc.Load(fs); // byte[] bytes = Encoding.Default.GetBytes(testDoc.OuterXml); // var test = CustomAES.Encrypt(bytes, "password"); // File.WriteAllBytes("C:\\Users\\Nutzer\\Desktop\\encryptedTestFile.sfdb", test); //} var file = File.ReadAllBytes("C:\\Users\\Nutzer\\Desktop\\TestZip.sfzf"); var aesAlgorithm = new AesAlgorithm(); //var test = aesAlgorithm.Encrypt(file, "password"); var testSalt = "testSalt"; var testSaltBytes = Encoding.ASCII.GetBytes(testSalt); //var allBytes = ByteHelper.AppendTwoByteArrays(test,testSaltBytes); //File.WriteAllBytes("C:\\Users\\Nutzer\\Desktop\\encryptedTestFile.sfdb", allBytes); }
public string CreateVerificationEmail(UserMaster user, string token) { AesAlgorithm aesAlgorithm = new AesAlgorithm(); var key = string.Join(":", new string[] { DateTime.Now.Ticks.ToString(), user.UserId.ToString() }); var encrypt = aesAlgorithm.EncryptToBase64String(key); var linktoverify = $"{_appSettings.VerifyResetPasswordUrl}?key={HttpUtility.UrlEncode(encrypt)}&hashtoken={HttpUtility.UrlEncode(token)}"; var stringtemplate = new StringBuilder(); stringtemplate.Append("Welcome"); stringtemplate.Append("<br/>"); stringtemplate.Append($"Dear {user.FirstName}{user.LastName}"); stringtemplate.Append("<br/>"); stringtemplate.Append("Please click the following link to reset your password."); stringtemplate.Append("<br/>"); stringtemplate.Append($"Reset password link : <a target='_blank' href={linktoverify}>Link</a>"); stringtemplate.Append("<br/>"); stringtemplate.Append("If the link does not work, copy and paste the URL into a new browser window. The URL will expire in 24 hours for security reasons."); stringtemplate.Append("<br/>"); stringtemplate.Append("Best regards,"); stringtemplate.Append("Frapper"); stringtemplate.Append("<br/>"); return(stringtemplate.ToString()); }
public string SendVerificationEmail(User user, string token) { AesAlgorithm aesAlgorithm = new AesAlgorithm(); var key = string.Join(":", new string[] { DateTime.Now.Ticks.ToString(), user.UserId.ToString() }); var encrypt = aesAlgorithm.EncryptToBase64String(key); var linktoverify = _appSettings.VerifyResetPasswordUrl + "?key=" + HttpUtility.UrlEncode(encrypt) + "&hashtoken=" + HttpUtility.UrlEncode(token); var stringtemplate = new StringBuilder(); stringtemplate.Append("Welcome"); stringtemplate.Append("<br/>"); stringtemplate.Append("Dear " + user.FullName); stringtemplate.Append("<br/>"); stringtemplate.Append("Please click the following link to reset your password."); stringtemplate.Append("<br/>"); stringtemplate.Append("Reset password link : <a target='_blank' href=" + linktoverify + ">Link</a>"); stringtemplate.Append("<br/>"); stringtemplate.Append("If the link does not work, copy and paste the URL into a new browser window. The URL will expire in 24 hours for security reasons."); stringtemplate.Append("<br/>"); stringtemplate.Append("Best regards,"); stringtemplate.Append("Saineshwar Begari"); stringtemplate.Append("<br/>"); return(stringtemplate.ToString()); }
public ActionResult Login(LoginViewModel loginViewModel) { try { if (ModelState.IsValid) { if (!this.IsCaptchaValid("Captcha is not valid")) { ModelState.AddModelError("", "Error: captcha is not valid."); return(View(new LoginViewModel())); } if (!_iUserMaster.CheckUsernameExists(loginViewModel.Username)) { ModelState.AddModelError("", "Invalid Credentails"); return(View(loginViewModel)); } AesAlgorithm aesAlgorithm = new AesAlgorithm(); var usermasterModel = _iUserMaster.GetUserByUsername(loginViewModel.Username); var storedpassword = aesAlgorithm.DecryptString(_password.GetPasswordbyUserId(usermasterModel.UserId)); if (storedpassword == loginViewModel.Password) { Session["UserID"] = usermasterModel.UserId; Session["Username"] = usermasterModel.UserName; int UserID = Convert.ToInt32(usermasterModel.UserId); VW_ProcessByUserManager context = new VW_ProcessByUserManager(new DataContext()); VW_ProcessByUser objVW_ProcessByUser = context.GetProcessByUserById(UserID); if (objVW_ProcessByUser != null) { Session["UserProcess"] = objVW_ProcessByUser.ProcessName != null ? objVW_ProcessByUser.ProcessName : ""; } var user = _iUserMaster.GetUserById(UserID); SetOnlineUser(UserID.ToString()); Session["UserPhoto"] = user.ImageName; if (_savedAssignedRoles.GetAssignedRolesbyUserId(usermasterModel.UserId) != null) { // 1 is SuperAdmin if (_savedAssignedRoles.GetAssignedRolesbyUserId(usermasterModel.UserId).RoleId == Convert.ToInt32(ConfigurationManager.AppSettings["SuperAdminRolekey"])) { Session["Role"] = _savedAssignedRoles.GetAssignedRolesbyUserId(usermasterModel.UserId).RoleId; Session["RoleName"] = "SuperAdmin"; return(RedirectToAction("Dashboard", "SuperDashboard")); } // 2 is User if (_savedAssignedRoles.GetAssignedRolesbyUserId(usermasterModel.UserId).RoleId == Convert.ToInt32(ConfigurationManager.AppSettings["UserRolekey"])) { Session["Role"] = _savedAssignedRoles.GetAssignedRolesbyUserId(usermasterModel.UserId).RoleId; Session["RoleName"] = "User"; return(RedirectToAction("Dashboard", "UserDashboard")); } // 3 is Admin if (_savedAssignedRoles.GetAssignedRolesbyUserId(usermasterModel.UserId).RoleId == Convert.ToInt32(ConfigurationManager.AppSettings["AdminRolekey"])) { Session["Role"] = _savedAssignedRoles.GetAssignedRolesbyUserId(usermasterModel.UserId).RoleId; Session["RoleName"] = "Admin"; return(RedirectToAction("Dashboard", "AdminDashboard")); } } else { ModelState.AddModelError("", "Access Not Assigned"); return(View(loginViewModel)); } return(RedirectToAction("Dashboard", "Dashboard")); } else { ModelState.AddModelError("", "Invalid Credentails"); return(View(loginViewModel)); } } else { return(View(loginViewModel)); } } catch (Exception) { throw; } }
/// <summary> /// Encrypts the full file name using the file Key and Iv values with AES-OFB algorithm and encodes it to <see href="https://en.wikipedia.org/wiki/Base64">Base64</see>. /// Since Base64 contains forward slash ('/') which is a <see href="https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file">reserved character</see> that can't be used for file naming, every '/' is replaced with '$'. /// </summary> /// <param name="name">Full name of the file (name + extension) that is being encrypted.</param> /// <param name="aes">AES algorithm used for decryption of the full file name.</param> public void NameEncryption(string name, AesAlgorithm aes) { EncryptedName = Convert.ToBase64String(aes.Encrypt(Encoding.ASCII.GetBytes(name))); EncryptedName = EncryptedName.Replace('/', '$'); }
public ActionResult Login(LoginViewModel loginViewModel) { try { if (ModelState.IsValid) { //if (!this.IsCaptchaValid("Captcha is not valid")) //{ // ModelState.AddModelError("", "Error: captcha is not valid."); // return View(new LoginViewModel()); //} if (!_password.CheckEmailExists(loginViewModel.EmailId)) { ModelState.AddModelError("", "Invalid Credentails"); return(View(loginViewModel)); } AesAlgorithm aesAlgorithm = new AesAlgorithm(); var usermasterModel = _password.GetCheckUserEmailExists(loginViewModel.EmailId); var storedpassword = aesAlgorithm.DecryptString(_password.GetPasswordbyUserId(usermasterModel.UserEmail)); if (storedpassword == loginViewModel.Password) { Session["UserID"] = usermasterModel.UserId; Session["Username"] = usermasterModel.UserEmail; if (_savedAssignedRoles.GetAssignedRolesbyUserId(usermasterModel.UserId) != null) { // 1 is SuperAdmin if (_savedAssignedRoles.GetAssignedRolesbyUserId(usermasterModel.UserId).RoleId == Convert.ToInt32(ConfigurationManager.AppSettings["SuperAdminRolekey"])) { Session["Role"] = _savedAssignedRoles.GetAssignedRolesbyUserId(usermasterModel.UserId).RoleId; return(RedirectToAction("Dashboard", "SuperDashboard")); } // 2 is User if (_savedAssignedRoles.GetAssignedRolesbyUserId(usermasterModel.UserId).RoleId == Convert.ToInt32(ConfigurationManager.AppSettings["UserRolekey"])) { Session["Role"] = _savedAssignedRoles.GetAssignedRolesbyUserId(usermasterModel.UserId).RoleId; return(RedirectToAction("Dashboard", "UserDashboard")); } // 3 is Admin if (_savedAssignedRoles.GetAssignedRolesbyUserId(usermasterModel.UserId).RoleId == Convert.ToInt32(ConfigurationManager.AppSettings["CustomerRolekey"])) { Session["Role"] = _savedAssignedRoles.GetAssignedRolesbyUserId(usermasterModel.UserId).RoleId; return(RedirectToAction("Dashboard", "AdminDashboard")); } } else { ModelState.AddModelError("", "Access Not Assigned"); return(View(loginViewModel)); } return(RedirectToAction("Dashboard", "Dashboard")); } else { ModelState.AddModelError("", "Invalid Credentails"); return(View(loginViewModel)); } } else { return(View(loginViewModel)); } } catch (Exception) { throw; } }
/// <summary> /// Decodes the file name and then decrypts it using the file Key and Iv values with AES-OFB algorithm. /// </summary> /// <param name="aes">AES algorithm used for decryption of the full file name.</param> /// <returns>Full name of the file (name + extension).</returns> public string NameDecryption(AesAlgorithm aes) { return(Encoding.ASCII.GetString(aes.Decrypt(Convert.FromBase64String(EncryptedName.Replace('$', '/'))))); }
/// <summary> /// Opens a <see cref="Fortress"/> and loads the database. /// </summary> public void BuildFortress(string fortressFullPath, string fortressName, string password) { try { Logger.log.Info($"Start opening the fortress {fortressFullPath}..."); var aesHelper = new AesHelper(); // =========================================================== Unzip the fortress - Read salt var unzippedFortress = ZipHelper.UnzipSavedZip(fortressFullPath); using (unzippedFortress) { var entryOfSalt = fortressName + "/salt" + TermHelper.GetTextFileEnding(); var saltEntry = unzippedFortress.GetEntry(entryOfSalt); var saltBytes = new byte[32]; using (var stream = saltEntry.Open()) { saltBytes = ByteHelper.ReadBytesOfStream(stream); } CurrentFortressData.Salt = saltBytes; Logger.log.Debug("Unzipped fortress - Salt bytes read."); // =========================================================== Create masterkey var hashedKey = aesHelper.CreateKey(password, 256, saltBytes); password = string.Empty; // Delete the password in plaintext from RAM var masterKey = new Masterkey(hashedKey); hashedKey = null; // Hash also Logger.log.Debug("Masterkey created."); // =========================================================== Decrypt database var entryOfDatabase = fortressName + "/" + TermHelper.GetDatabaseTerm() + TermHelper.GetDatabaseEnding(); var databaseEntry = unzippedFortress.GetEntry(entryOfDatabase); var aesAlg = new AesAlgorithm(); using (var stream = databaseEntry.Open()) { var dbBytes = ByteHelper.ReadBytesOfStream(stream); var decryptedDb = aesAlg.Decrypt(dbBytes, masterKey.Value, saltBytes); Logger.log.Info($"Decrypted {TermHelper.GetDatabaseTerm()}"); // =========================================================== Unzip database // We distinguish between sensible data and normal data. We put the sensible data into the secureDatacache. var unzippedByteEntriesOfDb = ZipHelper.GetEntriesFromZipArchive(decryptedDb); // These are the entries in byte arrays decryptedDb = null; // Add to secureDC. foreach (var sensibleBytes in unzippedByteEntriesOfDb.Item2.Item2.ToList()) // ToList() otherwise the iterations throws exception { AddToSecureMemoryDC(unzippedByteEntriesOfDb.Item2.Item1.Pop(), unzippedByteEntriesOfDb.Item2.Item2.Pop()); } foreach (var bytes in unzippedByteEntriesOfDb.Item1.ToList()) // Add not sensible data to the "unsecure" DC. { AddToUnsecureMemoryDC(BuildModelsOutOfBytes <ModelBase>(unzippedByteEntriesOfDb.Item1.Pop())); } unzippedByteEntriesOfDb = null; } // Track the security parameters for scans later. SecurityParameterProvider.Instance.UpdateHash(nameof(Fortress), fortressFullPath); } } catch (Exception ex) { ex.SetUserMessage(WellKnownExceptionMessages.DataExceptionMessage()); throw ex; } }
/// <summary> /// Creates a new <see cref="Fortress"/> with a <see cref="MasterKey"/> and saves it encrypted. /// </summary> internal void WriteFortress(Fortress fortress, bool overwrite = false) { try { Logger.log.Info("Starting to write a fortress..."); var databasePath = Path.Combine(fortress.FullPath, TermHelper.GetDatabaseTerm()); // =========================================================== Create the root directory IOPathHelper.CreateDirectory(fortress.FullPath); Logger.log.Debug($"Created outer walls {fortress.FullPath}."); // =========================================================== Create the sub directories for the database IOPathHelper.CreateDirectory(databasePath); Logger.log.Debug($"Created the {TermHelper.GetDatabaseTerm()}"); // =========================================================== Create the file which holds the salt to unlock the database StoreSalt(fortress.FullPath, fortress.Salt); Logger.log.Debug("Stored salt"); // =========================================================== Store the user Input and initial data in the database foreach (var modelList in _unsecureDatacache.Values) // UnsecureDatacache { foreach (var model in modelList) { StoreOne(model); } } foreach (var pair in _secureDatacache) { // We filter: Only if the sensible data has a parent we want to save it. Otherwise the parent has been deleted, // which makes the sensible counterpart useless. if (_unsecureDatacache.Values.Any(l => l.Any(m => m.Id == pair.Key))) { var byteModel = new ByteModel(pair.Key, pair.Value); StoreOne(null, true, byteModel); } } Logger.log.Debug("Stored fortress information."); // =========================================================== Zip only the database ZipHelper.ZipSavedArchives(databasePath, $"{databasePath}{TermHelper.GetZippedFileEnding()}"); Directory.Delete(databasePath, true); Logger.log.Debug($"{TermHelper.GetDatabaseTerm()} has been zipped."); // =========================================================== Encrypt the database var aesAlg = new AesAlgorithm(); // Read all bytes from the database directory var data = File.ReadAllBytes($"{databasePath}{TermHelper.GetZippedFileEnding()}"); // Encrypt it var encryptedData = aesAlg.Encrypt(data, fortress.MasterKey.Value, fortress.Salt); // Write the encrypted file File.WriteAllBytes($"{databasePath}{TermHelper.GetDatabaseEnding()}", encryptedData); // Delete the zip File.Delete($"{databasePath}{TermHelper.GetZippedFileEnding()}"); Logger.log.Debug($"Encrypted {TermHelper.GetDatabaseTerm()}"); // =========================================================== Zip the whole fortress if (overwrite) { File.Delete($"{fortress.FullPath}{TermHelper.GetZippedFileEnding()}"); } ZipHelper.ZipSavedArchives(fortress.FullPath, $"{fortress.FullPath}{TermHelper.GetZippedFileEnding()}"); Directory.Delete(fortress.FullPath, true); Logger.log.Debug("Fortress has been zipped."); Logger.log.Info("Fortress has been sucessfully written!"); } catch (Exception ex) { // Delete all changes that have been made to this point. We do not want half-built fortresses. if (Directory.Exists(fortress.FullPath)) { Directory.Delete(fortress.FullPath, true); } if (File.Exists(Path.Combine(fortress.FullPath, TermHelper.GetZippedFileEnding()))) { File.Delete(fortress.FullPath + TermHelper.GetZippedFileEnding()); } ex.SetUserMessage(WellKnownExceptionMessages.DataExceptionMessage()); throw ex; } }
public ActionResult Create(CreateUserViewModel createUserViewModel, HttpPostedFileBase fileUpload) { try { if (createUserViewModel.UserId > 0) { ModelState.Remove("UserName"); ModelState.Remove("Password"); ModelState.Remove("ConfirmPassword"); ModelState.Remove("RoleId"); } if (ModelState.IsValid) { if (createUserViewModel.UserId == 0) { var isUser = _iUserMaster.CheckUsernameExists(createUserViewModel.UserName); if (isUser) { ModelState.AddModelError("", "Username already exists"); } AesAlgorithm aesAlgorithm = new AesAlgorithm(); var usermaster = AutoMapper.Mapper.Map <Usermaster>(createUserViewModel); string path = Server.MapPath("~/Content/UserImage/"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (fileUpload != null && fileUpload.ContentLength > 0) { string extension = Path.GetExtension(fileUpload.FileName); string newFileName = "u_" + DateTime.Now.Ticks + extension; usermaster.ImageName = newFileName; fileUpload.SaveAs(path + newFileName); } usermaster.Status = true; usermaster.CreateDate = DateTime.Now; usermaster.UserId = 0; usermaster.CreatedBy = Convert.ToInt32(Session["UserID"]); var userId = _iUserMaster.AddUser(usermaster); if (userId != -1) { var passwordMaster = new PasswordMaster { CreateDate = DateTime.Now, UserId = userId, PasswordId = 0, Password = aesAlgorithm.EncryptString(createUserViewModel.Password) }; var passwordId = _iPassword.SavePassword(passwordMaster); if (passwordId != -1) { var savedAssignedRoles = new SavedAssignedRoles() { RoleId = createUserViewModel.RoleId, UserId = userId, AssignedRoleId = 0, Status = true, CreateDate = DateTime.Now }; _savedAssignedRoles.AddAssignedRoles(savedAssignedRoles); TempData["MessageCreateUsers"] = "User Created Successfully"; } } } else { var usermaster = AutoMapper.Mapper.Map <Usermaster>(createUserViewModel); string path = Server.MapPath("~/Content/UserImage/"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (fileUpload != null && fileUpload.ContentLength > 0) { string extension = Path.GetExtension(fileUpload.FileName); string newFileName = "u_" + DateTime.Now.Ticks + extension; usermaster.ImageName = newFileName; fileUpload.SaveAs(path + newFileName); } usermaster.Status = true; usermaster.CreateDate = DateTime.Now; usermaster.UserId = createUserViewModel.UserId; usermaster.CreatedBy = Convert.ToInt32(Session["UserID"]); var userId = _iUserMaster.UpdateUser(usermaster); } return(RedirectToAction("Create", "CreateUsers")); } else { return(View("Create", createUserViewModel)); } } catch { throw; } }