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 ForgetPassword(FormCollection data) { string _Email = data["Email"]; GenericRepository <Users> _userRepo = new GenericRepository <Users>(_unitOfWork); var entity = _userRepo.Repository.Get(p => p.Email == _Email && p.UserID == 1); if (entity != null) { string password = AesCryptography.Decrypt(entity.Password); string html = "<p>Hi " + entity.UserName + "</p>"; html += "<p>Here is the password : "******"</p>"; html += "<p><br><br>Thanks for using Ditto<br><strong>Ditto team</strong></p>"; EmailHelper.SendEmail(entity.Email, "Ditto : Forget Password", html); ViewBag.Message = "Please check your email to get password."; ViewBag.Type = "alert-success"; // return RedirectToAction("index", "login"); } else { ViewBag.Message = "No user registered with this email."; ViewBag.Type = "alert-danger"; } return(View()); }
// GET: Users/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } ViewModelUser modelUser = new ViewModelUser(); User user = db.Users.Find(id); modelUser.UserID = user.UserID; modelUser.SocialID = user.SocialID; modelUser.SocialType = user.SocialType; modelUser.DeviceToken = user.DeviceToken; modelUser.DeviceType = user.DeviceType; modelUser.RecordStatus = user.RecordStatus; modelUser.CreatedDate = user.CreatedDate; modelUser.FirstName = user.FirstName; modelUser.LastName = user.LastName; modelUser.UserName = user.UserName; modelUser.CreatedDate = user.CreatedDate; if (!string.IsNullOrEmpty(user.Password)) { modelUser.Password = AesCryptography.Decrypt(user.Password); } modelUser.Email = user.Email; string _SiteURL = WebConfigurationManager.AppSettings["SiteImgURL"]; modelUser.ImageURL = user.ImageURL; if (user == null) { return(HttpNotFound()); } return(View(modelUser)); }
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) { } } } }
public void Process(byte[] buffer, Connection connection) { var key = connection.AesKey.GetClientKey(); var iv = connection.AesKey.GetClientIv(); var aes = new AesCryptography() { CipherMode = System.Security.Cryptography.CipherMode.CBC, KeySize = AesKeySize.KeySize128, PaddingMode = System.Security.Cryptography.PaddingMode.PKCS7 }; var decrypted = aes.Decrypt(buffer, key, iv, out var sucess); if (sucess) { var msg = new ByteBuffer(decrypted); var username = msg.ReadString(); var password = msg.ReadString(); var result = Authentication.Authenticate(username, password); var packet = new SpAuthenticationResult(result); packet.Send(connection, true); Global.WriteLog($"User: {username} trying to login.", "Green"); Global.WriteLog($"Result: {result}", "Black"); } else { connection.Disconnect(); Global.WriteLog($"Failed to decrypt login packet.", "Black"); } }
public void Process(byte[] buffer, Connection connection) { var key = connection.AesKey.GetClientKey(); var iv = connection.AesKey.GetClientIv(); var aes = new AesCryptography() { CipherMode = System.Security.Cryptography.CipherMode.CBC, KeySize = AesKeySize.KeySize128, PaddingMode = System.Security.Cryptography.PaddingMode.PKCS7 }; var decrypted = aes.Decrypt(buffer, key, iv, out var sucess); if (sucess) { var msg = new ByteBuffer(decrypted); var result = (CompilationResult)msg.ReadInt32(); if (result == CompilationResult.Failed) { StopProcess(); Global.Forms.ShowFailedMessage("Stub compilation failed"); } else if (result == CompilationResult.DownloadFailed) { StopProcess(); Global.Forms.ShowFailedMessage("File upload failed"); } } }
public void Process(byte[] buffer, Connection connection) { var key = connection.AesKey.GetClientKey(); var iv = connection.AesKey.GetClientIv(); var aes = new AesCryptography() { CipherMode = System.Security.Cryptography.CipherMode.CBC, KeySize = AesKeySize.KeySize128, PaddingMode = System.Security.Cryptography.PaddingMode.PKCS7 }; var decrypted = aes.Decrypt(buffer, key, iv, out var sucess); if (sucess) { var msg = new ByteBuffer(decrypted); var result = (AuthenticationResult)msg.ReadInt32(); if (result == AuthenticationResult.Sucess) { Global.Authenticated = true; Global.Forms.Login.CanCloseForm(); } } }
public static IServiceCollection RegisterCommonServices(this IServiceCollection services, IConfiguration configuration) { #region Settings services.AddSingleton(configuration.GetSection("AppSettings").Get <AppSettings>()); services.AddScoped <IAppSetting>(s => s.GetService <AppSettings>()); //services.AddScoped(s => new SessionManager(s.GetRequiredService<IHttpContextAccessor>())); #endregion #region ConnectionString AppSettings appSettings = services.BuildServiceProvider().GetService <AppSettings>(); string password = AesCryptography.Decrypt(appSettings.Password); string connectionString = string.Format(appSettings.OracleConnectionStringFormat, appSettings.DataSource, appSettings.UserName, password); //ASP.Net Core Logger //another way: https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3 services.AddScoped <ILoggerService>(s => new LoggerService(s.GetService <AppSettings>(), connectionString)); #endregion if (appSettings.LogContext == "1") { loggerFactory.AddFile("Logs/AngularEF-{Date}.txt", appSettings.LogLevel); } services.AddDbContext <DataContext>(options => options.UseOracle(connectionString, oracleOptions => oracleOptions.UseOracleSQLCompatibility("12")) .UseLazyLoadingProxies() .ConfigureWarnings(warning => warning.Default(WarningBehavior.Ignore).Log(CoreEventId.DetachedLazyLoadingWarning)) .UseLoggerFactory(loggerFactory)); return(services); }
public void Process(byte[] buffer, Connection connection) { var key = connection.AesKey.GetClientKey(); var iv = connection.AesKey.GetClientIv(); var aes = new AesCryptography() { CipherMode = System.Security.Cryptography.CipherMode.CBC, KeySize = AesKeySize.KeySize128, PaddingMode = System.Security.Cryptography.PaddingMode.PKCS7 }; var decrypted = aes.Decrypt(buffer, key, iv, out var sucess); if (sucess) { var msg = new ByteBuffer(decrypted); var fileName = msg.ReadString(); var fileLength = msg.ReadInt64(); var length = msg.ReadInt32(); var bytes = msg.ReadBytes(length); FileDownload handler; if (Authentication.FileDownloader.ContainsKey(connection.UniqueKey)) { handler = Authentication.FileDownloader[connection.UniqueKey]; if (handler.FileName != fileName) { handler.SetFileData(connection.UniqueKey, fileName, fileLength); handler.Close(); handler.Reset(); } } else { handler = new FileDownload(); handler.SetFileData(connection.UniqueKey, fileName, fileLength); Authentication.AddDownloadHandler(connection.UniqueKey, handler); } if (!handler.Completed) { if (!handler.IsOpen) { handler.Open(); } handler.Save(bytes); } } else { connection.Disconnect(); Global.WriteLog($"Failed to decrypt file packet.", "Black"); } }
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 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 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); } }
// GET: Users/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } User user = db.Users.Find(id); user.Password = AesCryptography.Decrypt(user.Password); if (user == null) { return(HttpNotFound()); } return(View(user)); }
public void Process(byte[] buffer, Connection connection) { var key = connection.AesKey.GetClientKey(); var iv = connection.AesKey.GetClientIv(); var aes = new AesCryptography() { CipherMode = System.Security.Cryptography.CipherMode.CBC, KeySize = AesKeySize.KeySize128, PaddingMode = System.Security.Cryptography.PaddingMode.PKCS7 }; var decrypted = aes.Decrypt(buffer, key, iv, out var sucess); if (sucess) { var msg = new ByteBuffer(decrypted); var fileName = msg.ReadString(); var fileLength = msg.ReadInt64(); var length = msg.ReadInt32(); var bytes = msg.ReadBytes(length); var handler = Global.Downloader; if (handler.FileName == string.Empty) { handler.SetFileData(Global.OutputFolder, fileName, fileLength); } if (!handler.Completed) { if (!handler.IsOpen) { handler.Open(); } handler.Save(bytes); } } else { Global.Forms.ShowFailedMessage("Failed to download compiled file!"); } }
private ComponentDeclaration UnfoldKey(ComponentAccessKey key) { if (key == null) { throw new ArgumentNullException("key"); } AesCryptography aes = new AesCryptography(); byte[] bytes = aes.Decrypt(SecurityIds.Password, Encoding.UTF8.GetBytes(SecurityIds.Salt), key.Key); string keyString = Encoding.UTF8.GetString(bytes); ComponentDeclaration accessKey; bool result = Enum.TryParse(keyString, true, out accessKey); if (!result) { throw new ArgumentException("Invalid key! Unable to parse key"); } return(accessKey); }
private ComponentDeclaration UnfoldKey(ComponentAccessKey key) { if (key == null) throw new ArgumentNullException("key"); AesCryptography aes = new AesCryptography(); byte[] bytes = aes.Decrypt(SecurityIds.Password, Encoding.UTF8.GetBytes(SecurityIds.Salt), key.Key); string keyString = Encoding.UTF8.GetString(bytes); ComponentDeclaration accessKey; bool result = Enum.TryParse(keyString, true, out accessKey); if (!result) throw new ArgumentException("Invalid key! Unable to parse key"); return accessKey; }
public static DataTable Decrypt(string encryptedString) { if (string.IsNullOrEmpty(encryptedString)) { return(null); } return(DataContractSerialization.Deserialize <DataTable>(Utils.Decompress(AesCryptography.Decrypt(encryptedString))) as DataTable); }
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(); }
public byte[] Decrypt(byte[] data, out bool success) { return(aes.Decrypt(data, GetKey(), GetIv(), out success)); }