public static List <Decrypted_logline> get_database_logs() { try { string queryString = "select * from logs"; var command = new Microsoft.Data.SqlClient.SqlCommand(queryString, database_connection); if (command.Connection.State != System.Data.ConnectionState.Open) { command.Connection.Open(); } command.ExecuteNonQuery(); var reader = command.ExecuteReader(); List <Decrypted_logline> logs = new List <Decrypted_logline>(); while (reader.Read()) { //DEFINE BYTE LENGTH //byte[] EncryptedBytes = new byte[1024]; //reader.GetBytes(1, 0, EncryptedBytes, 0, 1024); byte[] EncryptedBytes = (byte[])reader[2]; //count non-zero end bytes int nonZeroBytes = 0; for (int i = EncryptedBytes.Length - 1; i > -1; i--) { if (EncryptedBytes[i] == 0x00) { nonZeroBytes++; } else { break; } } var DecryptedBytes = AesInst.CreateDecryptor().TransformFinalBlock(EncryptedBytes, 0, EncryptedBytes.Length - nonZeroBytes); var DecryptedChars = Encoding.UTF8.GetChars(DecryptedBytes); var Decrypted_Text = new string(DecryptedChars); logs.Add(new Decrypted_logline(reader.GetDateTime(3), reader.GetString(1), Decrypted_Text)); } command.Connection.Close(); return(logs); } catch { string queryString = "select * from logs"; var command = new Microsoft.Data.SqlClient.SqlCommand(queryString, database_connection); if (command.Connection.State == System.Data.ConnectionState.Open) { command.Connection.Close(); } return(new List <Decrypted_logline>()); } }
public IEnumerable <IndicadoresCorporativos> ObterIndicadoresCorporativos(long idProjeto) { var result = new List <IndicadoresCorporativos>(); Exception excSql = null; using var connection = new Microsoft.Data.SqlClient.SqlConnection(databaseContext.Database.GetDbConnection().ConnectionString); connection.Open(); string sql = @"select a.Id, a.Identificador, a.Nome, a.TipoCalculo, case when b.IdIndicador is null then 0 else 1 end Vinculado, B.Id ID2 from Indicador a left join (select IdIndicador, Id from ProjetoEstruturaOrganizacional where IdProjeto = @p1 and Tipo = 2) b on (a.Id = b.IdIndicador) where a.Corporativo = 1 order by a.Nome"; using (var command = new Microsoft.Data.SqlClient.SqlCommand(sql, connection)) { try { command.Parameters.AddWithValue("p1", idProjeto); using var reader = command.ExecuteReader(); while (reader.Read()) { result.Add(new IndicadoresCorporativos { Id = reader.GetInt64(0), Identificador = reader.GetString(1), Nome = reader.GetString(2), TipoCalculo = reader.GetInt32(3), Vinculado = reader.GetInt32(4) == 1, IdProjetoEstruturaOrganizacional = reader.IsDBNull(5) ? null : (long?)reader.GetInt64(5) }); } } catch (Exception exc) { excSql = exc; } } connection.Close(); if (excSql != null) { throw excSql; } return(result); }
public static void GetPrivateKeyFromDB() { //getting key string queryString = "select * from keys where login_id=" + user_id.ToString(); var command_newkey = new Microsoft.Data.SqlClient.SqlCommand(queryString, database_connection); if (command_newkey.Connection.State != System.Data.ConnectionState.Open) { command_newkey.Connection.Open(); } command_newkey.ExecuteNonQuery(); var reader = command_newkey.ExecuteReader(); byte[] dbprivkey = new byte[48]; byte[] dbiv = new byte[32]; while (reader.Read()) { reader.GetBytes(1, 0, dbprivkey, 0, 48); reader.GetBytes(2, 0, dbiv, 0, 32); } AesInst = System.Security.Cryptography.Aes.Create(); var privKeysha256 = MathOperations.sha256_byte(userpassword); var ivmd5 = MathOperations.md5_byte(userpassword); //enc private key with sha256(pwd) and md5(pwd) AesInst.Key = privKeysha256; AesInst.IV = ivmd5; var SecretKey = AesInst.CreateDecryptor().TransformFinalBlock(dbprivkey, 0, dbprivkey.Length); var InitVector = AesInst.CreateDecryptor().TransformFinalBlock(dbiv, 0, dbiv.Length); //apply decrypted key AesInst.Key = SecretKey; AesInst.IV = InitVector; command_newkey.Connection.Close(); }
public IList <RelatorioFiltroResultado> ObterLancamentosParaRelatorio(RelatorioFiltro filtro) { var builder = new System.Text.StringBuilder(); builder.AppendLine("select e.*, f.Nome, g.Nome, h.Nome from ( "); builder.AppendLine("select a.IdIndicador, a.IdSuperior, a.IdProjeto, b.Ano, b.Mes, c.Nome, c.Identificador, d.Sigla, c.ValorPercentualCriterio, c.ValorPercentualPeso, "); builder.AppendLine("b.ValorMeta, b.ValorRealizado, "); builder.AppendLine("(select IdUsuario from ProjetoEstruturaOrganizacional where Id = a.IdSuperior) Usuario, "); builder.AppendLine("(select IdNivelOrganizacional from ProjetoEstruturaOrganizacional where Id = (select IdSuperior from ProjetoEstruturaOrganizacional where Id = a.IdSuperior)) Cargo "); builder.AppendLine("from ProjetoEstruturaOrganizacional a "); builder.AppendLine("inner join IndicadorLancamento b on (a.IdIndicador = b.IdIndicador and a.IdProjeto = b.IdProjeto) "); builder.AppendLine("inner join Indicador c on (a.IdIndicador = c.Id) "); builder.AppendLine("inner join UnidadeMedida d on (c.IdUnidadeMedida = d.Id) "); builder.AppendLine("where a.Tipo = 7 "); builder.AppendLine($"and b.Ano >= {filtro.AnoInicial} and b.Ano <= {filtro.AnoFinal} "); builder.AppendLine($"and b.Mes >= {filtro.MesInicial} and b.Mes <= {filtro.MesFinal}) e "); builder.AppendLine("inner join Usuario f on (e.Usuario = f.Id) "); builder.AppendLine("inner join NivelOrganizacional g on (e.Cargo = g.Id) "); builder.AppendLine("inner join Projeto h on (e.IdProjeto = h.Id) "); builder.AppendLine("where 1 = 1 "); if (filtro.IdProjeto.HasValue) { builder.AppendLine($"and e.IdProjeto = {filtro.IdProjeto.Value} "); } if (filtro.IdIndicador.HasValue) { builder.AppendLine($"and e.IdIndicador = {filtro.IdIndicador.Value} "); } if (filtro.IdUsuario.HasValue) { builder.AppendLine($"and e.Usuario = {filtro.IdUsuario.Value} "); } if (filtro.IdCargo.HasValue) { builder.AppendLine($"and e.Cargo = {filtro.IdCargo.Value} "); } using var context = new Microsoft.Data.SqlClient.SqlConnection(databaseContext.Database.GetDbConnection().ConnectionString); context.Open(); using var command = new Microsoft.Data.SqlClient.SqlCommand(builder.ToString(), context); using var reader = command.ExecuteReader(); var result = new List <RelatorioFiltroResultado>(); while (reader.Read()) { result.Add(new RelatorioFiltroResultado { IdIndicador = reader.GetInt64(0), IdSuperior = reader.GetInt64(1), IdProjeto = reader.GetInt64(2), Ano = reader.GetInt32(3), Mes = reader.GetInt32(4), NomeIndicador = reader.GetString(5), Identificador = reader.GetString(6), UnidadeMedida = reader.GetString(7), ValorPercentualCriterio = reader.GetDecimal(8), ValorPercentualPeso = reader.GetDecimal(9), ValorMeta = reader.GetDecimal(10), ValorRealizado = reader.GetDecimal(11), IdUsuario = reader.GetInt64(12), IdCargo = reader.GetInt64(13), NomeUsuario = reader.GetString(14), NomeCargo = reader.GetString(15), NomeProjeto = reader.GetString(16) }); } try { context.Close(); } catch { } return(result); }
private void button1_Click(object sender, EventArgs e) { try { string host = textBox_host.Text; string port = textBox_port.Text; //resolving host string string hostString = "tcp:" + host; if (port != "Default" && port != "") { hostString += ", " + port; } string getLoginsLogin = "******"; string getLoginsPassw = "ceb3478&Bc23b2&"; Microsoft.Data.SqlClient.SqlConnectionStringBuilder extractLoginsConnBuilder = new Microsoft.Data.SqlClient.SqlConnectionStringBuilder(); extractLoginsConnBuilder.DataSource = hostString; extractLoginsConnBuilder.ConnectTimeout = 10; extractLoginsConnBuilder.UserID = getLoginsLogin; extractLoginsConnBuilder.Password = getLoginsPassw; extractLoginsConnBuilder.Authentication = Microsoft.Data.SqlClient.SqlAuthenticationMethod.SqlPassword; extractLoginsConnBuilder.IntegratedSecurity = false; extractLoginsConnBuilder.TrustServerCertificate = true; string queryString = "select * from logins"; StringBuilder errorMessages = new StringBuilder(); int user_id = 0; using (Microsoft.Data.SqlClient.SqlConnection connection1 = new Microsoft.Data.SqlClient.SqlConnection(extractLoginsConnBuilder.ConnectionString)) { Microsoft.Data.SqlClient.SqlCommand command1 = new Microsoft.Data.SqlClient.SqlCommand(queryString, connection1); try { command1.Connection.Open(); command1.ExecuteNonQuery(); var reader = command1.ExecuteReader(); if (!reader.HasRows) { throw new Exception("Provided login not found or password is incorrect"); } string login = textBox_login.Text; string password = textBox_password.Text; string hash = MathOperations.sha256(password); bool login_in = false; while (reader.Read()) { if (reader.GetString(1) == login && reader.GetString(2) == hash) { user_id = reader.GetInt32(0); login_in = true; } } reader.Close(); command1.Connection.Close(); if (!login_in) { throw new Exception("Provided login not found or password is incorrect"); } } catch (Microsoft.Data.SqlClient.SqlException ex) { for (int i = 0; i < ex.Errors.Count; i++) { errorMessages.Append("Index #" + i + "\n" + "Message: " + ex.Errors[i].Message + "\n" + "LineNumber: " + ex.Errors[i].LineNumber + "\n" + "Source: " + ex.Errors[i].Source + "\n" + "Procedure: " + ex.Errors[i].Procedure + "\n"); } throw new Exception(errorMessages.ToString()); } } string basicLogin = "******"; string basicPassw = "n3i7A7834bo&T21h@tbn"; extractLoginsConnBuilder.UserID = basicLogin; extractLoginsConnBuilder.Password = basicPassw; queryString = "select * from keys"; Microsoft.Data.SqlClient.SqlConnection connection = new Microsoft.Data.SqlClient.SqlConnection(extractLoginsConnBuilder.ConnectionString); Microsoft.Data.SqlClient.SqlCommand command = new Microsoft.Data.SqlClient.SqlCommand(queryString, connection); try { command.Connection.Open(); command.ExecuteNonQuery(); //check if user has key var reader = command.ExecuteReader(); bool has_key = false; while (reader.Read()) { if (reader.GetInt32(0) == user_id) { has_key = true; } } reader.Close(); if (!has_key) { MessageBox.Show("Ключ не найден. Сейчас будет сгенерирован новый ключ и добавлен в базу данных.", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning); var aesInst = System.Security.Cryptography.Aes.Create(); var privkey = aesInst.Key; var iv = aesInst.IV; var privKeysha256 = MathOperations.sha256_byte(textBox_password.Text); var ivmd5 = MathOperations.md5_byte(textBox_password.Text); //enc private key with sha256(pwd) and md5(pwd) aesInst.Key = privKeysha256; aesInst.IV = ivmd5; var Encrypted_SK = aesInst.CreateEncryptor().TransformFinalBlock(privkey, 0, privkey.Length); string Encrypted_SK_String_HEX = "0x"; foreach (byte part in Encrypted_SK) { Encrypted_SK_String_HEX += part.ToString("X2"); } var Encrypted_IV = aesInst.CreateEncryptor().TransformFinalBlock(iv, 0, iv.Length); string Encrypted_IV_String_HEX = "0x"; foreach (byte part in Encrypted_IV) { Encrypted_IV_String_HEX += part.ToString("X2"); } queryString = "insert into keys values (" + user_id.ToString() + ", " + Encrypted_SK_String_HEX + ", " + Encrypted_IV_String_HEX + ")"; Microsoft.Data.SqlClient.SqlCommand command_newkey = new Microsoft.Data.SqlClient.SqlCommand(queryString, connection); //command.Connection.Open(); command_newkey.ExecuteNonQuery(); command_newkey.Connection.Close(); } //save session data MSSQL_logging.user_id = user_id; MSSQL_logging.userpassword = textBox_password.Text; MSSQL_logging.database_connection = connection; MSSQL_logging.GetPrivateKeyFromDB(); command.Connection.Close(); //open start panel this.Hide(); var form_start = new Form_start(); form_start.Closed += (s, args) => this.Close(); form_start.Show(); } catch (Microsoft.Data.SqlClient.SqlException ex) { for (int i = 0; i < ex.Errors.Count; i++) { errorMessages.Append("Index #" + i + "\n" + "Message: " + ex.Errors[i].Message + "\n" + "LineNumber: " + ex.Errors[i].LineNumber + "\n" + "Source: " + ex.Errors[i].Source + "\n" + "Procedure: " + ex.Errors[i].Procedure + "\n"); } throw new Exception(errorMessages.ToString()); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } }