public ActionResult Create(ViewModelUser ViewUser) { User user = new User(); if (ModelState.IsValid) { user.FirstName = ViewUser.FirstName; user.LastName = ViewUser.LastName; user.UserName = ViewUser.UserName; if (!string.IsNullOrEmpty(ViewUser.Password)) { user.Password = AesCryptography.Encrypt(ViewUser.Password); } user.Email = ViewUser.Email; string _SiteURL = WebConfigurationManager.AppSettings["SiteImgURL"]; user.ImageURL = _SiteURL + "/ProfileImage/" + ViewUser.ImageURL_data.FileName; var path = Path.Combine(Server.MapPath("~/Content/Upload/ProfileImage"), ViewUser.ImageURL_data.FileName); ViewUser.ImageURL_data.SaveAs(path); user.RecordStatus = "Active"; user.CreatedDate = DateTime.Now; db.Users.Add(user); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(user)); }
public void StartEncryptAndDecrypt() { var generator = new CryptographyKey(); if (!generator.IsKeyCreated()) { var result = generator.CanCreateKey(""); if (!result) { // A chave não foi criada, deseja usar a padrão? } var key = generator.IsKeyCreated() ? generator.GetKey() : generator.GetDefaultKey(); var iv = generator.IsKeyCreated() ? generator.GetIv() : generator.GetDefaultIv(); var aes = new AesCryptography { CipherMode = System.Security.Cryptography.CipherMode.ECB, KeySize = CryptographyKeySize.KeySize128, PaddingMode = System.Security.Cryptography.PaddingMode.PKCS7 }; var hash = Hash.Compute("Texto para exemplo!"); var encrypted = aes.Encrypt(hash, generator.GetKey(), generator.GetIv(), out var success); if (success) { var decrypted = aes.Decrypt(hash, key, iv, out success); if (success) { } } } }
private ByteBuffer Encript(Connection connection) { encrypted = true; var buffer = new ByteBuffer(); var header = msg.ReadInt32(); var bytes = msg.ReadBytes(msg.Length()); var key = connection.AesKey.GetKey(); var iv = connection.AesKey.GetIv(); var aes = new AesCryptography() { CipherMode = System.Security.Cryptography.CipherMode.CBC, KeySize = AesKeySize.KeySize128, PaddingMode = System.Security.Cryptography.PaddingMode.PKCS7 }; var encripted = aes.Encrypt(bytes, key, iv); if (encripted != null) { buffer = new ByteBuffer(4 + encripted.Length); buffer.Write(header); buffer.Write(encripted); } return(buffer); }
public ActionResult ChangePassword(FormCollection data) { int AdminID = Numerics.GetInt(Session["AdminID"]); if (AdminID > 0) { if (data.Count > 0) { string oldPassword = AesCryptography.Encrypt(data["OldPassword"]); string newPassword = AesCryptography.Encrypt(data["NewPassword"]); GenericRepository <Users> _userRepo = new GenericRepository <Users>(_unitOfWork); Users entity = _userRepo.Repository.Get(p => p.Password == oldPassword && p.UserID == AdminID); if (entity != null) { entity.Password = newPassword; _userRepo.Repository.Update(entity); ViewBag.Message = "Password updated successfully."; ViewBag.Type = "alert-success"; } else { ViewBag.Message = "Old Password is incorrect."; ViewBag.Type = "alert-danger"; } } return(View()); } else { return(RedirectToAction("index", "login")); } }
public static string Encrypt(DataTable dt) { if (dt == null) { return(null); } return(AesCryptography.Encrypt(Utils.Compress(DataContractSerialization.Serialize(dt)))); }
public void AesTests(string plainText, string password) { var aes = new AesCryptography(password); var encrypted = aes.Encrypt(plainText); var decrypted = aes.Decrypt(encrypted); decrypted.Should().Be(plainText, "the decrypted string should be unchanged from the original string"); }
public void TestAesCrypto() { var crypto = new AesCryptography(); const string originalString = "AES cryptography"; var cryptoString = crypto.Encrypt(originalString); var decryptString = crypto.Decrypt(cryptoString); Assert.AreEqual(originalString, decryptString); }
public void EncryptDecrypt_TamperingEncryptedData_ThrowsCryptographicException() { AesCryptography aes = new AesCryptography(); byte[] cipherText = aes.Encrypt(SecurityIds.Password, Encoding.UTF8.GetBytes(SecurityIds.Salt), Encoding.UTF8.GetBytes(CLEAR_TEXT)); byte[] inClearText = aes.Decrypt(SecurityIds.Password, Encoding.UTF8.GetBytes(SecurityIds.Salt), cipherText); // Now let's do some tampering... cipherText[30]++; aes.Decrypt(SecurityIds.Password, Encoding.UTF8.GetBytes(SecurityIds.Salt), cipherText); }
public ActionResult Login(UserLogin login, string ReturnUrl = "") { string message = ""; using (oposeeDbEntities db = new oposeeDbEntities()) { //if ("*****@*****.**" != login.EmailID) //// if ("*****@*****.**" != input.Email) //{ // ViewBag.Message = "Invalid Admin Email"; // ViewBag.Type = "alert-danger"; // Session.RemoveAll(); // return View(); //} var v = db.Users.Where(a => a.Email == login.EmailID && a.IsAdmin == true).FirstOrDefault(); if (v != null) { if (string.Compare(AesCryptography.Encrypt(login.Password), v.Password) == 0) { int timeout = login.RememberMe ? 525600 : 20; // 525600 min = 1 year var ticket = new FormsAuthenticationTicket(login.EmailID, login.RememberMe, timeout); string encrypted = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted); cookie.Expires = DateTime.Now.AddMinutes(timeout); cookie.HttpOnly = true; Response.Cookies.Add(cookie); if (Url.IsLocalUrl(ReturnUrl)) { return(Redirect(ReturnUrl)); } else { Session["AdminID"] = login.EmailID; return(RedirectToAction("Index", "Home")); } } else { message = "Invalid credential provided"; } } else { message = "Invalid credential provided"; } } ViewBag.Message = message; Session.RemoveAll(); return(View()); }
public ActionResult Edit(ViewModelUser ViewUser) { if (ModelState.IsValid) { User user = new User(); user.FirstName = ViewUser.FirstName; user.LastName = ViewUser.LastName; user.UserName = ViewUser.UserName; if (!string.IsNullOrEmpty(ViewUser.Password)) { user.Password = AesCryptography.Encrypt(ViewUser.Password); } user.Email = ViewUser.Email; string _SiteURL = WebConfigurationManager.AppSettings["SiteImgURL"]; if (ViewUser.ImageURL_data != null) { user.ImageURL = _SiteURL + "/ProfileImage/" + ViewUser.ImageURL_data.FileName; var path = Path.Combine(Server.MapPath("~/Content/Upload/ProfileImage"), ViewUser.ImageURL_data.FileName); ViewUser.ImageURL_data.SaveAs(path); } else { user.ImageURL = _SiteURL + "/ProfileImage/oposee-profile.png"; } user.CreatedDate = ViewUser.CreatedDate; //user.ImageURL = ViewUser.ImageURL; user.UserID = ViewUser.UserID; user.DeviceType = ViewUser.DeviceType; user.DeviceToken = ViewUser.DeviceToken; user.SocialID = ViewUser.SocialID; user.SocialType = ViewUser.SocialType; user.RecordStatus = "Active"; user.ModifiedDate = DateTime.Now; db.Entry(user).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(ViewUser)); }
public void EncryptDecrypt_ValidPasswordSalt_AreEqual() { AesCryptography aes = new AesCryptography(); byte[] cipherText = aes.Encrypt(SecurityIds.Password, Encoding.UTF8.GetBytes(SecurityIds.Salt), Encoding.UTF8.GetBytes(CLEAR_TEXT)); byte[] inClearText = aes.Decrypt(SecurityIds.Password, Encoding.UTF8.GetBytes(SecurityIds.Salt), cipherText); Assert.AreEqual(CLEAR_TEXT, Encoding.UTF8.GetString(inClearText)); try { // Now let's do some tampering... cipherText[30]++; aes.Decrypt(SecurityIds.Password, Encoding.UTF8.GetBytes(SecurityIds.Salt), cipherText); Assert.Fail("The 'Decrypt' method did not throw an exception eventhough data was tamered with!"); } catch (Exception ex) { Assert.IsTrue(ex is CryptographicException); } }
public async Task <ExternalAuthentication> GetAsync(ulong discordUserId, ExternalService service) { var userId = (long)discordUserId; var dbExternalAuth = await _botContext.ExternalAuthentication .Where(ea => ea.User.DiscordUserId == userId) .FirstOrDefaultAsync(ea => ea.Service == service).ConfigureAwait(false); if (dbExternalAuth == null) { return(null); } var auth = new ExternalAuthentication { AccessToken = _aes.Decrypt(dbExternalAuth.AccessTokenAes), TokenType = _aes.Decrypt(dbExternalAuth.TokenTypeAes), Scope = _aes.Decrypt(dbExternalAuth.ScopeAes), RefreshToken = _aes.Decrypt(dbExternalAuth.RefreshTokenAes), ExpiresIn = int.Parse(_aes.Decrypt(dbExternalAuth.ExpiresInAes)) }; if (dbExternalAuth.LastRefreshed + TimeSpan.FromSeconds(auth.ExpiresIn - 60) > DateTime.UtcNow) { return(auth); } // Get New Token var newToken = await UpdateAsync(auth.RefreshToken, service).ConfigureAwait(false); // Update DB dbExternalAuth.AccessTokenAes = _aes.Encrypt(newToken.AccessToken); dbExternalAuth.ExpiresInAes = _aes.Encrypt(newToken.ExpiresIn.ToString()); dbExternalAuth.LastRefreshed = DateTime.UtcNow; await _botContext.SaveChangesAsync().ConfigureAwait(false); // Update return object auth.AccessToken = newToken.AccessToken; auth.ExpiresIn = newToken.ExpiresIn; return(auth); }
public ActionResult Index(InputLogin input) { if (ModelState.IsValid) { Users entity = null; if ("*****@*****.**" != input.Email) // if ("*****@*****.**" != input.Email) { ViewBag.Message = "Invalid Admin Email"; ViewBag.Type = "alert-danger"; Session.RemoveAll(); return(View(input)); } string _password = AesCryptography.Encrypt(input.Password); GenericRepository <Users> _userRepo = new GenericRepository <Users>(_unitOfWork); entity = _userRepo.Repository.Get(p => p.Email == input.Email && p.Password == _password); if (entity != null) { Session["AdminID"] = entity.UserID; Session["FullName"] = entity.UserName; Session["ThumbnailURL"] = entity.ThumbnailURL; Session["ImageURL"] = entity.ImageURL; return(RedirectToAction("Index", "Users")); } else { ViewBag.Message = "Invalid email or password"; ViewBag.Type = "alert-danger"; } } Session.RemoveAll(); return(View(input)); }
static void Main(string[] args) { #region Testing encryption/decryption bool shouldTest = false; if (shouldTest) { AesCryptography aes = new AesCryptography(); var password = "******"; var salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; var ct1 = aes.Encrypt(password, salt, Encoding.UTF8.GetBytes("Alice; Bob; Eve;: PerformAct1")); Console.WriteLine(Convert.ToBase64String(ct1)); var ct2 = aes.Encrypt(password, salt, Encoding.UTF8.GetBytes("Alice; Bob; Eve;: PerformAct2")); Console.WriteLine(Convert.ToBase64String(ct2)); var pt1 = aes.Decrypt(password, salt, ct1); Console.WriteLine(Encoding.UTF8.GetString(pt1)); var pt2 = aes.Decrypt(password, salt, ct2); Console.WriteLine(Encoding.UTF8.GetString(pt2)); // Now check tampering try { ct1[30]++; aes.Decrypt(password, salt, ct1); Console.WriteLine("Error: tamper detection failed."); } catch (Exception ex) { Console.WriteLine("Success: tampering detected."); Console.WriteLine(ex.ToString()); } Console.ReadLine(); } #endregion string COMPARE_SILENT = "SILENT"; string COMPARE_HELP = "HELP"; string[] cmdArgs = Environment.GetCommandLineArgs(); foreach (string arg in cmdArgs) { if (arg.ToUpper() == COMPARE_SILENT) { ConsoleEnabled = false; } if (arg.ToUpper() == COMPARE_HELP) { ConsoleEnabled = true; #region Help output to console // 12345678901234567890123456789012345678901234567890123456789012345678901234567890 Output("╔══════════════════════════════════════════════════════════════════════════════╗"); Output("║ Code Analyser ║"); Output("╠══════════════════════════════════════════════════════════════════════════════╣"); Output("║ ║"); Output("║ Purpose The application is designed to search files for suspect code ║"); Output("║ constructions, i.e. try-catch statements suppressing exceptions ║"); Output("║ from being handled. ║"); Output("║ ║"); Output("║ The type of code constructions that are matched during the search ║"); Output("║ is specified through regular expressions in the applications ║"); Output("║ configuration file. Multiple regular expressions can be added to ║"); Output("║ the configuration file as well as what directories the search ║"); Output("║ should include, what directories should be excluded, the type of ║"); Output("║ files to include in the search. ║"); Output("║ ║"); Output("║ ║"); Output("║ Result: A resulting xml file containing the result of the search will be ║"); Output("║ created in the execution directory, 'Analyser.xml'. Just open it ║"); Output("║ in a browser - it will be transformed into html by the associated ║"); Output("║ xslt file. ║"); Output("║ ║"); Output("║ ║"); Output("║ How to: The application can be run with no arguments. The following ║"); Output("║ arguments are allowed: ║"); Output("║ ║"); Output("║ <help> Will show this dialog. ║"); Output("║ ║"); Output("║ <silent> Indicates whether output from the client should be ║"); Output("║ enabled. Adding the argument 'silent' will disable ║"); Output("║ output to the command line. ║"); Output("║ ║"); Output("║ NOTE: Using the 'silent' argument will not disable output from ║"); Output("║ the log system to the 'Console' target! If all messages ║"); Output("║ to the command line should be completely disabled then ║"); Output("║ disable the 'Console' target in the log system ║"); Output("║ configuration file as well. ║"); Output("║ ║"); Output("║ ║"); Output("║ Setup: Two configuration files (.config) are needed in order to execute ║"); Output("║ the application. Both files is expected to be located in the ║"); Output("║ applications execution directory. If not placed here the ║"); Output("║ application will fail. ║"); Output("║ ║"); Output("║ <hunter> Configuration file for setting up the include ║"); Output("║ directories, regular expressions etc. ║"); Output("║ ║"); Output("║ <log> Configuration file for setting up the log system that the ║"); Output("║ application uses. ║"); Output("║ ║"); Output("╚══════════════════════════════════════════════════════════════════════════════╝"); #endregion ConsoleEnabled = false; return; } } try { DirHandler.Instance.CurrentDirectory = Environment.CurrentDirectory; } catch (Exception e) { Console.WriteLine(BaseException.Format(null, -1, @"Failed to initialize 'Directory Handler' with current DIR? Unable to continue.", e)); Console.ReadLine(); return; } ApplicationManager am = null; try { am = new ApplicationManager(); } catch (Exception e) { Console.WriteLine(BaseException.Format(null, -1, @"Failed to construct the 'Application Manager'? Unable to continue.", e)); Console.ReadLine(); return; } try { am.Start(); } catch (CoordinationException ce) { Console.WriteLine(ce.ExceptionSummary()); Console.ReadLine(); return; } Output(ProxyHome.Instance.StatisticsProxy.ExtractTimerMeasurings()); // Shutdown the log system - should also empty all the queues before stopping. Out.Stop(); Console.ReadLine(); }
internal ComponentAccessKey GenerateComponentAccessKey(string password, string salt, IKeyConsumer keyConsumer) { #region Validate input arguments... if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentNullException("password"); } if (string.IsNullOrWhiteSpace(salt)) { throw new ArgumentNullException("salt"); } if (keyConsumer == null) { throw new ArgumentNullException("keyConsumer"); } #endregion // All flags are default cleared! ComponentDeclaration accessSetup = ComponentDeclaration.NotDefined; #region Setup the component access flags for the 'Configuration' component if (keyConsumer is IConfigurationProxy) { accessSetup = accessSetup | ComponentDeclaration.Configuration; accessSetup = accessSetup | ComponentDeclaration.Statistics; accessSetup = accessSetup | ComponentDeclaration.DataAccess; } #endregion #region Setup the component access flags for the 'Configuration' component if (keyConsumer is IConfigurationFactory) { accessSetup = accessSetup | ComponentDeclaration.Statistics; } #endregion #region Setup the component access flags for the 'Engine' component if (keyConsumer is IEngineProxy) { // Setup the component access flags for the configuration component. accessSetup = accessSetup | ComponentDeclaration.Configuration; accessSetup = accessSetup | ComponentDeclaration.Engine; accessSetup = accessSetup | ComponentDeclaration.Matches; accessSetup = accessSetup | ComponentDeclaration.Statistics; } #endregion #region Setup the component access flags for the 'Output' component if (keyConsumer is IOutputProxy) { // Setup the component access flags for the configuration component. accessSetup = accessSetup | ComponentDeclaration.Configuration; // accessSetup = accessSetup | ComponentDeclaration.Engine; accessSetup = accessSetup | ComponentDeclaration.Statistics; accessSetup = accessSetup | ComponentDeclaration.Matches; } #endregion #region Setup the component access flags for the 'Matches' component if (keyConsumer is IMatchProxy) { // Setup the component access flags for the configuration component. accessSetup = accessSetup | ComponentDeclaration.Statistics; accessSetup = accessSetup | ComponentDeclaration.DataAccess; } #endregion #region Setup the component access flags for the 'Statistics' component if (keyConsumer is IStatisticsProxy) { // Setup the component access flags for the configuration component. accessSetup = accessSetup | ComponentDeclaration.Statistics; } #endregion #region Setup the component access flags for the 'DataAccess' component if (keyConsumer is IDataAccessProxy) { // Setup the component access flags for the configuration component. accessSetup = accessSetup | ComponentDeclaration.DataAccess; accessSetup = accessSetup | ComponentDeclaration.Configuration; } #endregion // Create the description for the key - the description must declare // what components the flags give access to. string description = GenerateKeyDescription(accessSetup); // Let's do the actual encryption... AesCryptography aes = new AesCryptography(); byte[] bytes = aes.Encrypt(password, Encoding.UTF8.GetBytes(salt), Encoding.UTF8.GetBytes(accessSetup + "")); // Constructing the actual key for accessing the components... return(new ComponentAccessKey(bytes, description, keyConsumer)); }
internal ComponentAccessKey GenerateComponentAccessKey(string password, string salt, IKeyConsumer keyConsumer) { #region Validate input arguments... if (string.IsNullOrWhiteSpace(password)) throw new ArgumentNullException("password"); if (string.IsNullOrWhiteSpace(salt)) throw new ArgumentNullException("salt"); if (keyConsumer == null) throw new ArgumentNullException("keyConsumer"); #endregion // All flags are default cleared! ComponentDeclaration accessSetup = ComponentDeclaration.NotDefined; #region Setup the component access flags for the 'Configuration' component if (keyConsumer is IConfigurationProxy) { accessSetup = accessSetup | ComponentDeclaration.Configuration; accessSetup = accessSetup | ComponentDeclaration.Statistics; accessSetup = accessSetup | ComponentDeclaration.DataAccess; } #endregion #region Setup the component access flags for the 'Configuration' component if (keyConsumer is IConfigurationFactory) { accessSetup = accessSetup | ComponentDeclaration.Statistics; } #endregion #region Setup the component access flags for the 'Engine' component if (keyConsumer is IEngineProxy) { // Setup the component access flags for the configuration component. accessSetup = accessSetup | ComponentDeclaration.Configuration; accessSetup = accessSetup | ComponentDeclaration.Engine; accessSetup = accessSetup | ComponentDeclaration.Matches; accessSetup = accessSetup | ComponentDeclaration.Statistics; } #endregion #region Setup the component access flags for the 'Output' component if (keyConsumer is IOutputProxy) { // Setup the component access flags for the configuration component. accessSetup = accessSetup | ComponentDeclaration.Configuration; // accessSetup = accessSetup | ComponentDeclaration.Engine; accessSetup = accessSetup | ComponentDeclaration.Statistics; accessSetup = accessSetup | ComponentDeclaration.Matches; } #endregion #region Setup the component access flags for the 'Matches' component if (keyConsumer is IMatchProxy) { // Setup the component access flags for the configuration component. accessSetup = accessSetup | ComponentDeclaration.Statistics; accessSetup = accessSetup | ComponentDeclaration.DataAccess; } #endregion #region Setup the component access flags for the 'Statistics' component if (keyConsumer is IStatisticsProxy) { // Setup the component access flags for the configuration component. accessSetup = accessSetup | ComponentDeclaration.Statistics; } #endregion #region Setup the component access flags for the 'DataAccess' component if (keyConsumer is IDataAccessProxy) { // Setup the component access flags for the configuration component. accessSetup = accessSetup | ComponentDeclaration.DataAccess; accessSetup = accessSetup | ComponentDeclaration.Configuration; } #endregion // Create the description for the key - the description must declare // what components the flags give access to. string description = GenerateKeyDescription(accessSetup); // Let's do the actual encryption... AesCryptography aes = new AesCryptography(); byte[] bytes = aes.Encrypt(password, Encoding.UTF8.GetBytes(salt), Encoding.UTF8.GetBytes(accessSetup + "")); // Constructing the actual key for accessing the components... return new ComponentAccessKey(bytes, description, keyConsumer); }
public byte[] Encrypt(byte[] data, out bool success) { return(aes.Encrypt(data, GetKey(), GetIv(), out success)); }