Example #1
0
        public static byte[] DESEncrypt(byte[] message, string password)
        {
            try
            {
                // Encode message and password
                byte[] messageBytes  = message;
                byte[] passwordBytes = Encoding.UTF8.GetBytes(password);

                // Set encryption settings -- Use password for both key and init. vector
                DESCryptoServiceProvider provider  = new DESCryptoServiceProvider();
                ICryptoTransform         transform = provider.CreateEncryptor(passwordBytes, passwordBytes);
                CryptoStreamMode         mode      = CryptoStreamMode.Write;

                // Set up streams and encrypt
                MemoryStream memStream    = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);
                cryptoStream.Write(messageBytes, 0, messageBytes.Length);
                cryptoStream.FlushFinalBlock();

                // Read the encrypted message from the memory stream
                byte[] encryptedMessageBytes = new byte[memStream.Length];
                memStream.Position = 0;
                memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);

                Sistem.WriteLog(Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHY), "DESEncrypt(" + message + ") = " + Encoding.UTF8.GetString(encryptedMessageBytes), false, false, false, classColor);
                // Encode the encrypted message as base64 string
                return(encryptedMessageBytes);
            }
            catch (Exception ex)
            {
                Sistem.WriteLog(ex, Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHYCERROR) + "DESEncrypt(string message, string password)", true);
                error += ex.Message + "\n";
                return(null);
            }
        }
Example #2
0
        public static byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            try
            {
                byte[] decryptedData;

                //Create a new instance of RSACryptoServiceProvider.
                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    //Import the RSA Key information. This needs to include the private key information.
                    RSA.ImportParameters(RSAKeyInfo);

                    //Decrypt the passed byte array and specify OAEP padding.
                    //OAEP padding is only available on Microsoft Windows XP or later.
                    decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
                }
                Sistem.WriteLog(Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHY), "RSADecrypt(" + Encoding.UTF8.GetString(DataToDecrypt) + ") = " + Encoding.UTF8.GetString(decryptedData), false, false, true, classColor);
                return(decryptedData);
            }
            //Catch and display a CryptographicException to the console.
            catch (CryptographicException e)
            {
                Sistem.WriteLog(e, Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHYCERROR) + "RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)", true);
                error += e.Message + "\n";
                return(null);
            }
        }
Example #3
0
        public static OracleConnection dbGetOracleConnection()
        {
            if (oraConnection != null && oraConnection.State == System.Data.ConnectionState.Open)
            {
                return(oraConnection);
            }

            if (Sistem.LoadConfigFlag)
            {
                OracleConnection connection = null;
                for (int i = 0; i < oraConnectionString.Length; i++)
                {
                    connection = new OracleConnection(oraConnectionString[i]);
                    try
                    {
                        connection.Open();
                        break;
                    }
                    catch (Exception ex)
                    {
                        Sistem.WriteLog(ex, "DBAccessController.dbGetOracleConnection()");
                        connection = null;
                    }
                }
                return(connection);
            }
            else
            {
                return(null);
            }
        }
Example #4
0
        public static void AcceptCallback(IAsyncResult ar)
        {
            // Signal the main thread to continue.
            AllDone.Set();

            // Get the socket that handles the client request.
            Socket listener = (Socket)ar.AsyncState;
            Socket handler  = listener.EndAccept(ar);

            // Create the state object.
            StateObject state = new StateObject();

            state.workSocket = handler;

            Client client = new Client(ClientController.GetClientListCount());

            client.ConnectionTime = DateTime.Now;
            client.IP             = Convert.ToString(IPAddress.Parse(((IPEndPoint)state.workSocket.RemoteEndPoint).Address.ToString()));
            client.Port           = ((IPEndPoint)state.workSocket.RemoteEndPoint).Port;
            ClientController.AddClient(client);

            IPEndPoint clientEndPoint = (IPEndPoint)state.workSocket.RemoteEndPoint;

            Sistem.printF(string.Format("Client Connected: {0}", clientEndPoint.Address.ToString()), ConsoleColor.Green);

            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
        }
Example #5
0
        public static bool FileDecryptDES(string encryptedFilePath, string password)
        {
            bool   result;
            string fileDecryptedPath = encryptedFilePath.Substring(0, (encryptedFilePath.LastIndexOf(".")));

            try
            {
                byte[] buffer        = File.ReadAllBytes(encryptedFilePath);
                byte[] passwordBytes = Encoding.UTF8.GetBytes(password);

                // Set encryption settings -- Use password for both key and init. vector
                DESCryptoServiceProvider provider  = new DESCryptoServiceProvider();
                ICryptoTransform         transform = provider.CreateDecryptor(passwordBytes, passwordBytes);
                CryptoStreamMode         mode      = CryptoStreamMode.Write;

                // Set up streams and decrypt
                MemoryStream memStream    = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);
                cryptoStream.Write(buffer, 0, buffer.Length);
                cryptoStream.FlushFinalBlock();

                // Read decrypted message from memory stream
                byte[] decryptedFile = new byte[memStream.Length];
                memStream.Position = 0;
                memStream.Read(decryptedFile, 0, decryptedFile.Length);

                File.WriteAllBytes(fileDecryptedPath, decryptedFile);

                if (File.Exists(fileDecryptedPath))
                {
                    result = true;
                }
                else
                {
                    result = false;
                }

                if (result)
                {
                    Sistem.WriteLog(Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHY), "Create DES Decrypted File in " + fileDecryptedPath, false, false, true, classColor);
                }
                else
                {
                    Sistem.WriteLog(Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHY), "File  " + encryptedFilePath + " does not exist", false, false, true, classColor);
                }
            }
            catch (Exception ex)
            {
                Sistem.WriteLog(ex, Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHYCERROR) + "FileDecryptDES(string encryptedFilePath, string password)", true);
                error += ex.Message + "\n";
                result = false;
            }
            return(result);
        }
Example #6
0
 public DBAccessController()
 {
     if (Sistem.LoadConfigFlag)
     {
         createConnectionStrings();
     }
     else
     {
         Sistem.WriteLog("Debe completar el archivo de configuracion Config.xml antes de iniciar el sistema.", "DBAccessController()", true, true);
     }
 }
Example #7
0
 private static string DecodePassword(string password)
 {
     try
     {
         return(Encoding.UTF8.GetString(Convert.FromBase64CharArray(password.ToCharArray(), 0, password.Length)));
     }
     catch (Exception ex)
     {
         Sistem.WriteLog(ex, "AsyncSocketServer.DecryptMessage(string data)");
     }
     return(null);
 }
        public static async Task <bool> InterpretData(byte[] encryptedData)
        {
            bool result = false;

            try
            {
                Task   taskAction        = null;
                byte[] realDataEncrypted = new byte[encryptedData.Length - actionBytesCount];
                Buffer.BlockCopy(encryptedData, 0, realDataEncrypted, 0, realDataEncrypted.Length);
                byte[] actionBytes = new byte[20];
                Buffer.BlockCopy(encryptedData, encryptedData.Length - actionBytesCount, actionBytes, 0, actionBytes.Length);
                string action = Encoding.UTF8.GetString(actionBytes);
                string fileExtension;
                string dataEncripted     = Encoding.UTF8.GetString(realDataEncrypted);
                byte[] realDataDecrypted = SecurityController.DESDecrypt(realDataEncrypted, "susta250", false, false);

                if (action.Contains(Sistem.GetActionTag((int)Sistem.EnumActionTags.FILE)))
                {
                    int lastIdxOfDot = action.LastIndexOf(".");
                    fileExtension = action.Substring(lastIdxOfDot, action.Length - lastIdxOfDot).Replace(">", "").Replace("\0", "");
                    taskAction    = Task.Run(() => result = FileDataArrival(realDataDecrypted, fileExtension).Result);
                }

                if (action.Contains(Sistem.GetActionTag((int)Sistem.EnumActionTags.SQLMS)))
                {
                    taskAction = Task.Run(() => result = SqlCommandExecute(realDataDecrypted, action).Result);
                }
                else
                if (action.Contains(Sistem.GetActionTag((int)Sistem.EnumActionTags.SQLPL)))
                {
                    taskAction = Task.Run(() => result = OracleCommandExecute(realDataDecrypted, action).Result);
                }
                else
                {
                    result = false;
                }

                if (taskAction != null)
                {
                    taskAction.Wait();
                    taskAction.Dispose();
                }
            }
            catch (Exception ex)
            {
                Sistem.WriteLog(ex, "InterpretData(byte[] encryptedData)", true);
            }
            return(result);
        }
Example #9
0
        private static bool InterpretData(byte[] encryptedData)
        {
            bool result = false;

            try
            {
                Task action = Task.Run(() => result = InterpretDataActionController.CallInterpretData(encryptedData).Result);
                action.Wait();
            }
            catch (Exception ex)
            {
                Sistem.WriteLog(ex, "AsyncSocketServer.InterpretData(byte[] encryptedData)");
            }
            return(result);
        }
Example #10
0
 public static byte[] GetHashSha256(byte[] text, bool returnBytesAndTextAsBytes = true)
 {
     try
     {
         var    crypt  = new SHA256Managed();
         var    hash   = new StringBuilder();
         byte[] buffer = crypt.ComputeHash(text);
         Sistem.WriteLog(Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHY), "SHA256(" + Encoding.UTF8.GetString(text) + ") = " + hash.ToString().ToLower(), false, false, true, classColor);
         return(buffer);
     }
     catch (Exception ex)
     {
         Sistem.WriteLog(ex, Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHYCERROR) + "GetHashSha256(string text)", true);
         error += ex.Message + "\n";
         return(null);
     }
 }
Example #11
0
        public static bool UploadFile(string filePath)
        {
            bool result = false;

            try
            {
                if (System.IO.File.Exists(filePath))
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                Sistem.WriteLog(ex, "GoogleDriveController.UploadFile(string filePath)");
            }
            return(result);
        }
        public static async Task <bool> FileDataArrival(byte[] fileBuffer, string fileExtension)
        {
            bool result = false;

            try
            {
                string filename = Directory.GetCurrentDirectory() + "\\" + DateTime.Now.ToShortDateString().Replace("/", "-") + "-" + DateTime.Now.Hour + "hs" + DateTime.Now.Minute + fileExtension;
                File.WriteAllBytes(filename, fileBuffer);
                Sistem.WriteLog(Sistem.GetLogTag(Sistem.EnumLogTags.SERVER) + "File Created: " + filename, "InterpretDataActionController.InterpretData(string encryptedData)", true);
                result = true;
            }
            catch (Exception ex)
            {
                Sistem.WriteLog(ex, "FileDataArrival(byte[] fileBuffer, string fileExtension)", true);
            }
            return(result);
        }
        /// <summary>
        /// EXEC QUERY COMMANDS THAT RETURNS DATA
        /// </summary>
        /// <param name="dataDecrypted"></param>
        /// <param name="action"></param>
        /// <param name="returnDt"></param>
        /// <returns></returns>
        public static async Task <DataTable> SqlCommandExecute(byte[] dataDecrypted, string action, bool returnDt = true)
        {
            DataTable result = null;

            try
            {
                string         sqlCommandString = Encoding.UTF8.GetString(dataDecrypted);
                SqlCommand     cmd = new SqlCommand(Encoding.UTF8.GetString(dataDecrypted), DBAccessController.dbGetSqlConnection());
                SqlDataAdapter da  = new SqlDataAdapter(cmd);
                da.Fill(result);
            }
            catch (Exception ex)
            {
                Sistem.WriteLog(ex, "SqlCommandExecute(byte[] dataDecrypted, string action, bool returnDt = true)", true);
            }
            return(result);
        }
Example #14
0
        public static byte[] DESDecrypt(byte[] encryptedMessage, string password, bool returnBytes, bool toBase64 = false)
        {
            try
            {
                // Convert encrypted message and password to bytes
                byte[] encryptedMessageBytes = encryptedMessage;
                byte[] passwordBytes         = Encoding.UTF8.GetBytes(password);

                // Set encryption settings -- Use password for both key and init. vector
                DESCryptoServiceProvider provider  = new DESCryptoServiceProvider();
                ICryptoTransform         transform = provider.CreateDecryptor(passwordBytes, passwordBytes);
                CryptoStreamMode         mode      = CryptoStreamMode.Write;

                // Set up streams and decrypt
                MemoryStream memStream    = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);
                cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length);
                cryptoStream.FlushFinalBlock();

                // Read decrypted message from memory stream
                byte[] decryptedMessageBytes = new byte[memStream.Length];
                memStream.Position = 0;
                memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length);

                // Encode deencrypted binary data to base64 string
                byte[] result = null;
                if (toBase64)
                {
                    result = Encoding.UTF8.GetBytes(Convert.ToBase64String(decryptedMessageBytes));
                }
                else
                {
                    result = decryptedMessageBytes;
                }

                Sistem.WriteLog(Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHY), "DESDecrypt(" + encryptedMessage + ") = " + result, false, false, true, classColor);
                return(result);
            }
            catch (Exception ex)
            {
                Sistem.WriteLog(ex, Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHYCERROR) + "DESDecrypt(string encryptedMessage, string password, bool toBase64 = false)", true);
                error += ex.Message + "\n";
                return(null);
            }
        }
Example #15
0
        public static string Translate(string text, string toLanguaje, string sourceLanguaje = "")
        {
            string result = string.Empty;

            try
            {
                Console.OutputEncoding = System.Text.Encoding.Unicode;
                GoogleCredential  credential = GoogleCredential.FromFile(Directory.GetCurrentDirectory() + @"\GoogleTranslateCredentials.json");
                TranslationClient client     = TranslationClient.Create(credential);
                var response = client.TranslateText(text, toLanguaje, sourceLanguaje);
                result = response.TranslatedText;
            }
            catch (Exception ex)
            {
                Sistem.WriteLog(ex, "GoogleTranslateController.Translate(string text, string toLanguaje, string sourceLanguaje)");
            }
            return(result);
        }
Example #16
0
        public static string ToBase64Loop(string dataToEncode, int loop)
        {
            string result = dataToEncode;

            try
            {
                for (int i = 0; i < loop; i++)
                {
                    result = Convert.ToBase64String(Encoding.UTF8.GetBytes(result));
                }

                Sistem.WriteLog(Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHY) + "ToBase64Loop(" + dataToEncode + ") x" + loop.ToString() + " = " + result, "", false, false, true, classColor);
            }
            catch (Exception ex)
            {
                Sistem.WriteLog(ex, Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHYCERROR) + "ToBase64Loop(string dataToEncode, int loop)", true);
            }
            return(result);
        }
Example #17
0
        private static void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket handler = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = handler.EndSend(ar);
                Sistem.printF(string.Format("Sent {0} bytes to client.", bytesSent), ConsoleColor.Gray);

                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
            catch (Exception e)
            {
                Sistem.printF(e.ToString(), ConsoleColor.Red);
            }
        }
        public static async Task <bool> OracleCommandExecute(byte[] dataDecrypted, string action)
        {
            bool result = false;

            try
            {
                string        oracleCommandString = Encoding.UTF8.GetString(dataDecrypted);
                OracleCommand cmd         = new OracleCommand(oracleCommandString, DBAccessController.dbGetOracleConnection());
                int           afectedRows = cmd.ExecuteNonQuery();
                if (afectedRows > 0)
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                Sistem.WriteLog(ex, "OracleCommandExecute(byte[] dataDecrypted, string action)", true);
            }
            return(result);
        }
        /// <summary>
        /// EXEC NON QUERY COMMANDS WITH NO RETURN OF DATA
        /// </summary>
        /// <param name="dataDecrypted"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static async Task <bool> SqlCommandExecute(byte[] dataDecrypted, string action)
        {
            bool result = false;

            try
            {
                //INSERT, UPDATE AND DELETE
                string     sqlCommandString = Encoding.UTF8.GetString(dataDecrypted);
                SqlCommand cmd         = new SqlCommand(sqlCommandString, DBAccessController.dbGetSqlConnection());
                int        afectedRows = cmd.ExecuteNonQuery();
                if (afectedRows > 0)
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                Sistem.WriteLog(ex, "SqlCommandExecute(byte[] dataDecrypted, string action)", true);
            }
            return(result);
        }
Example #20
0
 public static bool ExecuteOracleCommand(string cmdText)
 {
     try
     {
         OracleCommand cmd = new OracleCommand(cmdText, dbGetOracleConnection());
         if (cmd.Connection == null)
         {
             return(false);
         }
         OracleDataAdapter da = new OracleDataAdapter(cmd);
         dataTable.Dispose();
         dataTable = new DataTable();
         da.Fill(dataTable);
         return(true);
     }
     catch (Exception ex)
     {
         Sistem.WriteLog(ex, "DBAccessController.ExecuteOracleCommand()");
         return(false);
     }
 }
Example #21
0
 public static byte[] MD5Hash(byte[] text, bool returnBytes = true)
 {
     try
     {
         StringBuilder            hash = new StringBuilder();
         MD5CryptoServiceProvider md5  = new MD5CryptoServiceProvider();
         byte[] buffer = md5.ComputeHash(text);
         for (int i = 0; i < buffer.Length; i++)
         {
             hash.Append(buffer[i].ToString("X2"));
         }
         Sistem.WriteLog(Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHY), "MD5(" + Encoding.UTF8.GetString(text) + ") = " + hash.ToString().ToLower(), false, false, true, classColor);
         return(buffer);
     }
     catch (Exception ex)
     {
         Sistem.WriteLog(ex, Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHYCERROR) + "MD5Hash(string text)", true);
         error += ex.Message + "\n";
         return(null);
     }
 }
Example #22
0
        public static void ReadCallback(IAsyncResult ar)
        {
            string content = string.Empty;

            // Retrieve the state object and the handler socket from the asynchronous state object.
            StateObject state   = (StateObject)ar.AsyncState;
            Socket      handler = state.workSocket;

            // Read data from the client socket.
            int bytesRead = handler.EndReceive(ar);

            if (bytesRead > 0)
            {
                // There  might be more data, so store the data received so far.
                state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));
                withrawBytes(ref buffer, state.buffer, bytesRead);
                // Check for end-of-file tag. If it is not there, read  more data.
                content = state.sb.ToString();

                if (content.Contains("<File.") || content.Contains("<SQL"))
                {
                    // All the data has been read from the  client. Display it on the console.
                    bool result = InterpretData(buffer);
                    if (result)
                    {
                        Sistem.printF(string.Format("Read {0} bytes from socket. \n", content.Length), ConsoleColor.Green);
                        // Echo the data encrypted back to the client.
                        Send(handler, buffer);
                    }
                    else
                    {
                        Send(handler, new byte[0]);
                    }
                }
                else                    // Not all data received. Get more.
                {
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                }
            }
        }
Example #23
0
        public static void StartListening()
        {
            // Establish the local endpoint for the socket.
            // The DNS name of the computer
            // running the listener is "host.contoso.com".
            IPHostEntry ipHostInfo    = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress   ipAddress     = ipHostInfo.AddressList[0];
            IPEndPoint  localEndPoint = new IPEndPoint(ipAddress, Port);

            // Create a TCP/IP socket.
            Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(100);

                Sistem.printF(Sistem.GetLogTag(Sistem.EnumLogTags.SERVER) + "Async Socket Server  ONLINE at " + ipAddress.ToString() + ":" + Port, ConsoleColor.Green);

                while (true)
                {
                    // Set the event to nonsignaled state.
                    AllDone.Reset();

                    // Start an asynchronous socket to listen for connections.
                    Sistem.printF(Sistem.GetLogTag(Sistem.EnumLogTags.SERVER) + "Waiting for a connection...", ConsoleColor.Gray);
                    listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);

                    // Wait until a connection is made before continuing.
                    AllDone.WaitOne();
                }
            }
            catch (Exception e)
            {
                Sistem.printF(e.ToString(), ConsoleColor.Red);
            }

            Sistem.printF("\nPress ENTER to continue...", ConsoleColor.Gray, false, false, true, true, true);
        }
Example #24
0
        public static string RSADecryption(string strText)
        {
            string decryptedData = string.Empty;

            try
            {
                var privateKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent><P>/aULPE6jd5IkwtWXmReyMUhmI/nfwfkQSyl7tsg2PKdpcxk4mpPZUdEQhHQLvE84w2DhTyYkPHCtq/mMKE3MHw==</P><Q>3WV46X9Arg2l9cxb67KVlNVXyCqc/w+LWt/tbhLJvV2xCF/0rWKPsBJ9MC6cquaqNPxWWEav8RAVbmmGrJt51Q==</Q><DP>8TuZFgBMpBoQcGUoS2goB4st6aVq1FcG0hVgHhUI0GMAfYFNPmbDV3cY2IBt8Oj/uYJYhyhlaj5YTqmGTYbATQ==</DP><DQ>FIoVbZQgrAUYIHWVEYi/187zFd7eMct/Yi7kGBImJStMATrluDAspGkStCWe4zwDDmdam1XzfKnBUzz3AYxrAQ==</DQ><InverseQ>QPU3Tmt8nznSgYZ+5jUo9E0SfjiTu435ihANiHqqjasaUNvOHKumqzuBZ8NRtkUhS6dsOEb8A2ODvy7KswUxyA==</InverseQ><D>cgoRoAUpSVfHMdYXW9nA3dfX75dIamZnwPtFHq80ttagbIe4ToYYCcyUz5NElhiNQSESgS5uCgNWqWXt5PnPu4XmCXx6utco1UVH8HGLahzbAnSy6Cj3iUIQ7Gj+9gQ7PkC434HTtHazmxVgIR5l56ZjoQ8yGNCPZnsdYEmhJWk=</D></RSAKeyValue>";

                var testData = Encoding.UTF8.GetBytes(strText);

                using (var rsa = new RSACryptoServiceProvider(1024))
                {
                    try
                    {
                        var base64Encrypted = strText;

                        // server decrypting data with private key
                        rsa.FromXmlString(privateKey);

                        var resultBytes    = Convert.FromBase64String(base64Encrypted);
                        var decryptedBytes = rsa.Decrypt(resultBytes, true);
                        decryptedData = Encoding.UTF8.GetString(decryptedBytes);
                        Sistem.WriteLog(Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHY), "Public Key RSADecryption(" + strText + ") = " + decryptedData, false, false, true, classColor);
                    }
                    finally
                    {
                        rsa.PersistKeyInCsp = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Sistem.WriteLog(ex, Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHYCERROR) + "RSADecryption(string strText)", true);
                error += ex.Message + "\n";
                return(null);
            }

            return(decryptedData);
        }
Example #25
0
        public static string GetHashSha256(byte[] text)
        {
            try
            {
                var    crypt  = new SHA256Managed();
                var    hash   = new StringBuilder();
                byte[] buffer = crypt.ComputeHash(text);

                for (int i = 0; i < buffer.Length; i++)
                {
                    hash.Append(buffer[i].ToString("x2"));
                }

                Sistem.WriteLog(Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHY), "SHA256(" + Encoding.UTF8.GetString(text) + ") = " + hash.ToString().ToLower(), false, false, true, classColor);
                return(hash.ToString());
            }
            catch (Exception ex)
            {
                Sistem.WriteLog(ex, Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHYCERROR) + "GetHashSha256(string text)", true);
                error += ex.Message + "\n";
                return(null);
            }
        }
Example #26
0
        public static string FromBase64Loop(string dataEncoded, int loop)
        {
            string result = dataEncoded;

            try
            {
                byte[] buffer    = Encoding.UTF8.GetBytes(dataEncoded);
                string charArray = string.Empty;
                for (int i = 0; i < loop; i++)
                {
                    charArray = Encoding.UTF8.GetString(buffer);
                    buffer    = Convert.FromBase64CharArray(charArray.ToCharArray(), 0, charArray.Length);
                }

                result = Encoding.UTF8.GetString(buffer);
                Sistem.WriteLog(Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHY) + "FromBase64Loop(" + dataEncoded + ") x" + loop.ToString() + " = " + result, "", false, false, true, classColor);
            }
            catch (Exception ex)
            {
                Sistem.WriteLog(ex, Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHYCERROR) + "FromBase64Loop(string dataEncoded, int loop)", true);
            }
            return(result);
        }
Example #27
0
        public static string RSAEncryption(string strText)
        {
            string base64Encrypted = string.Empty;

            try
            {
                var publicKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

                var testData = Encoding.UTF8.GetBytes(strText);

                using (var rsa = new RSACryptoServiceProvider(1024))
                {
                    try
                    {
                        // client encrypting data with public key issued by server
                        rsa.FromXmlString(publicKey.ToString());

                        var encryptedData = rsa.Encrypt(testData, true);

                        base64Encrypted = Convert.ToBase64String(encryptedData);

                        Sistem.WriteLog(Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHY), "Public Key RSAEncryption(" + strText + ") = " + base64Encrypted, false, false, true, classColor);
                    }
                    finally
                    {
                        rsa.PersistKeyInCsp = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Sistem.WriteLog(ex, Sistem.GetLogTag(Sistem.EnumLogTags.CRYPTOGRAPHYCERROR) + "RSAEncryption(string strText)", true);
                error += ex.Message + "\n";
                return(null);
            }
            return(base64Encrypted);
        }