コード例 #1
0
        private string GenerateNewMemoNumber()
        {
            // Decrypt file
            int counter = 1;

            try
            {
                if (System.IO.File.Exists(ClientHelper.GetMemoNumberFilePath()))
                {
                    counter = Cryptograph.DecryptObject <int>(ClientHelper.GetMemoNumberFilePath());

                    // Increment memo number and store it
                    counter += 1;
                    // Encrypt file with new memo number.
                    System.IO.File.Delete(ClientHelper.GetMemoNumberFilePath());
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(ex, "", false);
            }
            finally
            {
                Cryptograph.EncryptObject(counter, ClientHelper.GetMemoNumberFilePath());
            }
            return(counter.ToString());
        }
コード例 #2
0
ファイル: frmVideoLibrary.cs プロジェクト: videolib/dotnet
        private void frmVideoLibrary_Load(object sender, EventArgs e)
        {
            label11.Location = new System.Drawing.Point(panel4.Width / 2 - 150, 11);
            label2.Location  = new System.Drawing.Point(panel4.Width / 2 - 75, 15);

            _clientInfoFilePath = ClientHelper.GetClientInfoFilePath();
            //this.ClientInfoObject.LastAccessEndTime = DateTime.UtcNow;
            //Cryptograph.EncryptObject(this.ClientInfoObject, _clientInfoFilePath);

            CommonAppStateDataHelper.ClientInfoObject.LastAccessEndTime = this.ClientInfoObject.LastAccessEndTime = DateTime.Now;

            FileInfo clientInfoFileInfo = new FileInfo(ClientHelper.GetClientInfoFilePath());

            clientInfoFileInfo.Attributes &= ~FileAttributes.Hidden;
            Cryptograph.EncryptObject(this.ClientInfoObject, _clientInfoFilePath);
            clientInfoFileInfo.Attributes |= FileAttributes.Hidden;

            _clientRootPath          = ClientHelper.GetClientRootPath();
            _clientVideoRootFilePath = ClientHelper.GetClientVideoFilePath(this.ClientInfoObject.SchoolId, this.ClientInfoObject.SchoolCity);
            lblSessionYears.Text     = ClientHelper.GetSessionString(ClientInfoObject.SessionString);
            lblSchoolWelcome.Text    = ClientHelper.GetWelcomeString(ClientInfoObject.SchoolName, ClientInfoObject.SchoolCity, ClientInfoObject.SchoolId);
            // lblSchoolWelcome.Text = "Welcome, Only demo purpose only testing for demo, Indor, [0755-2549529]";
            lblExpireDate.Text = ClientHelper.GetExpiryDateString(ClientInfoObject.SessionEndDate);

            FillTreeView();
            treeView1.CollapseAll();

            UpdateTreeNodeSelection();
            FillVideoLibrary(this.treeView1.SelectedNode.Tag as TreeTag);
        }
コード例 #3
0
    public static void ReceivePacket(Packet packet)
    {
        try
        {
            bool         useEncrypt = packet.ReadBool();
            ServerPacket packetType = (ServerPacket)System.Enum.Parse(typeof(ServerPacket), packet.ReadString());

            int      lineCount = packet.ReadInt();
            string[] lineBuff  = new string[lineCount];

            for (int i = 0; i < lineCount; i++)
            {
                lineBuff[i] = (useEncrypt ? Cryptograph.Decrypt(Client.instance.clientKeys.priv, Cryptograph.SHA256Decrypt(packet.ReadString(), Client.instance.loginHash)) : packet.ReadString());
            }

            System.Action <Dictionary <string, object> > handler;
            if (ServerPacketHandlers.TryGetValue(packetType, out handler))
            {
                handler(ParseReceivedPacket(lineBuff));
            }
            else
            {
                Debug.Log("Failed to get packetHandler");
            }
        }
        catch (System.NullReferenceException ex)
        {
            Debug.Log($"An error ocurred during parsing some packet data ex: {ex.Message}");
        }
    }
コード例 #4
0
    public static void SendPacket(int toClient, ServerPacket type, Dictionary <string, object> packetData, bool udp = false, bool useEncrypt = true)
    {
        string        clientHash = Server.clients[toClient].loginHash;
        RSAParameters clientKey  = Server.clients[toClient].remoteKey;

        using (Packet packet = new Packet())
        {
            packet.Write(useEncrypt);

            // SEND: Packet subtype and quantity of data within packet.
            packet.Write(type.ToString());
            packet.Write(packetData.Count());

            // SEND: Packet data.
            foreach (KeyValuePair <string, object> pair in packetData)
            {
                string packet_line = $"{pair.Key}|{ParseSendObject(pair.Value)}|{pair.Value.GetType()}";
                packet.Write(!useEncrypt ? packet_line : Cryptograph.Encrypt(clientKey, Cryptograph.SHA256Encrypt(packet_line, clientHash)));
            }

            if (udp)
            {
                SendUDPData(toClient, packet);
            }
            else
            {
                SendTCPData(toClient, packet);
            }
        }
    }
コード例 #5
0
ファイル: FrmReg.cs プロジェクト: DanySharp/My-Dwonload-97-5
        private void button1_Click(object sender, EventArgs e)
        {
            if (usertxt.Text.Length < 3 || passtxt.Text.Length < 3)
            {
                MessageBox.Show("insert valid data ");
            }
            else
            {
                string dir = usertxt.Text;
                Directory.CreateDirectory(@"db" + dir);

                var Osw = new StreamWriter(@"db" + dir + @"\database.ls");

                string encrypuser  = Cryptograph.crypt(usertxt.Text);
                string encryptpass = Cryptograph.crypt(passtxt.Text);

                Osw.WriteLine(encrypuser);
                Osw.WriteLine(encryptpass);
                Osw.Dispose();
                Osw.Close();


                MessageBox.Show("User  created", usertxt.Text);

                this.Close();
                this.Dispose();
                Application.Restart();
                //  FrmLogin sd = new FrmLogin();
            }
        }
コード例 #6
0
        protected override void Initialize()
        {
            byte[] initialization = Cryptograph.Initialize();

            try
            {
                Socket.Send(initialization);
            }

            catch (Exception ex)
            {
                Log.Error(ex);
                throw;
            }

            string currentTime = DateTime.Now.ToString("HH:mm:ss");

            switch (Packet.LogLevel)
            {
            case LogLevel.Name:
                Log.Inform("[{0}][MapleClientHandler]: \n Sent Initialization packet (unencrypted).", currentTime);
                break;

            case LogLevel.Full:
                Log.Hex("Sent Initialization packet (unencrypted): ", initialization);
                break;

            case LogLevel.None:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
コード例 #7
0
        public async Task <ActionResult <dynamic> > Authenticate([FromBody] Usuario model)
        {
            try
            {
                if (model == null || model.UserName == null || model.Password == null)
                {
                    throw new Exception(Erro.DadosDePequisaInvalidos);
                }
                var password = Cryptograph.ComputeHashSh1(model.Password);
                var user     = _usuarioServico.Autenticacao(model.UserName, password);

                if (user == null)
                {
                    return(NotFound(new { message = "Usuário ou senha inválidos" }));
                }

                var token = TokenService.GenerateToken(user);
                user.Password = "";
                return(Ok(new
                {
                    user = user,
                    token = token
                }));
            }
            catch (Exception ex)
            {
                return(NotFound(new { message = ex.Message }));
            }
        }
コード例 #8
0
    /// <summary> Send a packet to endpoint </summary>
    /// <param name="action">Packet ID</param>
    /// <param name="packetData">Packet content</param>
    /// <param name="udp">UDP Enabled</param>
    /// <param name="useEncrypt">Use RSA/SHA256 encryption</param>
    public static void SendPacket(ClientPacket action, Dictionary <string, object> packetData, bool udp = false, bool useEncrypt = true)
    {
        string clientHash = Client.instance.loginHash;

        System.Security.Cryptography.RSAParameters clientKey = Client.instance.serverKey;

        using (Packet packet = new Packet((int)ClientPackets.welcomeReceived))
        {
            // SEND: Encryption enabled / packet ID.
            packet.Write(useEncrypt);
            packet.Write(action.ToString());

            // SEND: Data count & data converted in string format.
            packet.Write(packetData.Count());
            foreach (KeyValuePair <string, object> pair in packetData)
            {
                string packet_line = string.Join("|", new string[3] {
                    pair.Key, ParseSendObject(pair.Value), pair.Value.GetType().ToString()
                });
                Debug.Log(packet_line);
                packet.Write(!useEncrypt ? packet_line : Cryptograph.Encrypt(clientKey, Cryptograph.SHA256Encrypt(packet_line, clientHash)));
            }

            // SEND: With UDP style traffic if boolean "udp" is true, otherwise TCP.
            if (udp)
            {
                SendUDPData(packet);
            }
            else
            {
                SendTCPData(packet);
            }
        }
    }
コード例 #9
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                BackgroundProcessData currentData = e.Argument as BackgroundProcessData;
                if (currentData.CurrentVideoInfo != null)
                {
                    VideoInfo currentVideoInfo = currentData.CurrentVideoInfo;
                    currentVideoInfo.WatchCount++;
                    backgroundWorker1.ReportProgress(50, currentData);

                    string tempDirectory = Path.Combine(Path.GetTempPath(), "Temp");
                    Directory.CreateDirectory(tempDirectory);
                    backgroundWorker1.ReportProgress(97, currentData);

                    string tempFilePath = Path.Combine(tempDirectory, Path.GetFileName(currentData.OrignalVideoPath));
                    tempFileList.Add(tempFilePath);
                    Cryptograph.DecryptFile(currentData.OrignalVideoPath, tempFilePath);
                    currentData.DecryptedVideoPath = tempFilePath;
                    backgroundWorker1.ReportProgress(99, currentData);


                    SaveWatchedVideoCountOnFireBase(currentVideoInfo.VideoName, currentVideoInfo.WatchCount);
                    currentData.DecryptedVideoPath = "";
                    backgroundWorker1.ReportProgress(100, currentData);
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(ex, ex.Message, false);
                throw;
            }
        }
コード例 #10
0
        protected void Send(Packet outPacket)
        {
            short  packetOPCODE = outPacket.OperationCode;
            string packetName   = Enum.GetName(typeof(TSendOP), packetOPCODE);

            byte[] packetByteArray = outPacket.Array;
            string currentTime     = DateTime.Now.ToString("HH:mm:ss");

            outPacket.SafeFlip();
            Socket.Send(Cryptograph.Encrypt(outPacket.GetContent()));

            if (Enum.IsDefined(typeof(TSendOP), outPacket.OperationCode))
            {
                switch (Packet.LogLevel)
                {
                case LogLevel.Name:
                    Log.Inform("[{0}][ServerHandler]: \n Sent [{1}] packet.", currentTime, packetName);
                    break;

                case LogLevel.Full:
                    Log.Hex("Sent {0} packet: ", outPacket.GetContent(), Enum.GetName(typeof(TSendOP), outPacket.OperationCode));
                    break;

                case LogLevel.None:
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            else
            {
                Log.Hex("Sent unknown ({0:X2}) packet: ", packetByteArray, packetOPCODE);
            }
        }
コード例 #11
0
 public void Adicionar(Usuario usuario, string passwordConfirm)
 {
     if (!usuario.Password.Equals(passwordConfirm))
     {
         throw new Exception(Erro.SenhasNaoCombinam);
     }
     usuario.Password = Cryptograph.ComputeHashSh1(usuario.Password);
     _usuarioRepositorio.Adicionar(usuario);
 }
コード例 #12
0
ファイル: Edit.aspx.cs プロジェクト: rushbq/PKSign
    /// <summary>
    /// New TraceID
    /// </summary>
    /// <returns></returns>
    private string NewTraceID()
    {
        //產生TraceID
        long ts = Cryptograph.GetCurrentTime();

        Random rnd   = new Random();
        int    myRnd = rnd.Next(1, 99);

        return("{0}{1}".FormatThis(ts, myRnd));
    }
コード例 #13
0
 public void RightDecrypt()
 {
     if (Cryptograph.Decrypt(inptxt, "скорпион") == outptxt)
     {
         if (Cryptograph.Decrypt(inpword, "скорпион") == outpword)
         {
             Assert.Pass();
         }
     }
 }
        public override void Up()
        {
            Create.Table("Usuarios")
            .WithColumn("Id").AsInt32().Identity().PrimaryKey()
            .WithColumn("UserName").AsString(100)
            .WithColumn("Password").AsString(200)
            .WithColumn("Role").AsString(100)
            .WithColumn("Email").AsString(100);

            Insert.IntoTable("Usuarios").Row(new { UserName = "******", Password = Cryptograph.ComputeHashSh1("manager"), Role = "manager", Email = "*****@*****.**" });
        }
コード例 #15
0
        public void Dispose()
        {
            Terminate();

            Socket.Dispose();

            Cryptograph.Dispose();
            ReceiveDone.Dispose(); // TODO: Figure out why this crashes.

            CustomDispose();

            Log.Inform("{0} disposed.", Title);
        }
コード例 #16
0
        private void InitializeForm()
        {
            label11.Location     = new System.Drawing.Point(panel4.Width / 2 - 150, 11);
            lblAppTitle.Location = new System.Drawing.Point(panel4.Width / 2 - 75, 15);

            _clientRootPath     = ClientHelper.GetClientRootPath();
            _clientInfoFilePath = ClientHelper.GetClientInfoFilePath();
            this.ClientInfoObject.LastAccessEndTime = DateTime.Now;
            FileInfo clientInfoFileInfo = new FileInfo(ClientHelper.GetClientInfoFilePath());

            clientInfoFileInfo.Attributes &= ~FileAttributes.Hidden;
            // this.ClientInfoObject.LastAccessStartTime = DateTime.UtcNow;
            Cryptograph.EncryptObject(this.ClientInfoObject, _clientInfoFilePath);
            clientInfoFileInfo.Attributes |= FileAttributes.Hidden;

            FillTreeView();
            treeView1.CollapseAll();

            if (this.SelectedNode != null)
            {
                TreeNode[] searchedNode = this.treeView1.Nodes.Find(this.SelectedNode.Name, true);
                if (searchedNode.Length > 0)
                {
                    this.treeView1.SelectedNode = searchedNode[0];
                }
            }
            else
            {
                this.treeView1.SelectedNode = this.treeView1.Nodes[0];
            }

            lblSessionYears.Text = ClientHelper.GetSessionString(ClientInfoObject.SessionString);
            //lblWelcome.Text = ClientHelper.GetWelcomeString(ClientInfoObject.SchoolName, ClientInfoObject.SchoolCity, ClientInfoObject.SchoolId);

            lblExpireDate.Text = ClientHelper.GetExpiryDateString(ClientInfoObject.SessionEndDate);
            lblAppTitle.Text   = ClientHelper.GetRegisteredSchoolTitleString(ClientInfoObject.SchoolName, ClientInfoObject.SchoolCity, ClientInfoObject.SchoolId);

            AddPreviousVideoList();
            AddNextVideoList();

            if (EncryptedVideo)
            {
                PlayEncryptedVideo(CurrentVideoInfo.VideoFullUrl);
            }
            else
            {
                this.axWindowsMediaPlayer1.URL = CurrentVideoInfo.VideoFullUrl;
            }
        }
コード例 #17
0
 public AccountService(
     IStoredProcedureService storedProcedure,
     RandomMaker randomMaker,
     Cryptograph cryptograph,
     IAccountProfileService accountProfileService,
     IAccountDeviceService accountDeviceService,
     JwtHandler jwtHandler)
 {
     _storedProcedure       = storedProcedure;
     _randomMaker           = randomMaker;
     _cryptograph           = cryptograph;
     _accountProfileService = accountProfileService;
     _accountDeviceService  = accountDeviceService;
     _jwtHandler            = jwtHandler;
 }
コード例 #18
0
 public AccountController(
     IAccountService accountService,
     IAccountProfileService accountProfileService,
     RandomMaker randomMaker,
     Cryptograph cryptograph,
     IEmailService emailService,
     ISMSService smsService,
     IMemoryCache memoryCache)
 {
     _accountService        = accountService;
     _accountProfileService = accountProfileService;
     _randomMaker           = randomMaker;
     _cryptograph           = cryptograph;
     _emailService          = emailService;
     _smsService            = smsService;
     _memoryCache           = memoryCache;
 }
コード例 #19
0
        static void Main(string[] args)
        {
            Api api = new Api();

            var result = api.getData();

            var crypto = new Cryptograph();

            result.decifrado            = crypto.Decrypt(result.numero_casas, result.cifrado);
            result.resumo_criptografico = crypto.EncryptSHA1(result.decifrado);

            new JsonWriter(result);

            api.postData();

            Console.ReadLine();
        }
コード例 #20
0
    public static void ReceivePacket(int _fromClient, Packet packet)
    {
        try
        {
            // RECEIVE: Encryption enabled / packet ID.
            bool         useEncrypt = packet.ReadBool();
            ClientPacket packetType = (ClientPacket)System.Enum.Parse(typeof(ClientPacket), packet.ReadString());

            // RECEIVE: Data count & data converted in string format.
            string[] lineBuff = new string[packet.ReadInt()];
            for (int i = 0; i < lineBuff.Length; i++)
            {
                string line = packet.ReadString();
                if (useEncrypt)
                {
                    line = Cryptograph.Decrypt(Server.clients[_fromClient].clientKeys.privateKey, Cryptograph.SHA256Decrypt(packet.ReadString(), Server.clients[_fromClient].loginHash));
                }

                lineBuff[i] = line;
            }

            // HANDLE: Packet data and pass data to handler.
            Dictionary <string, object> packetData = ParseReceivedPacket(lineBuff);
            if (packetData != null)
            {
                System.Action <int, Dictionary <string, object> > handler;
                if (ClientPacketHandlers.TryGetValue(packetType, out handler))
                {
                    handler(_fromClient, packetData);
                }
                else
                {
                    Debug.Log($"Failed to get packetHandler of type {packetType}");
                }
            }
            else
            {
                Debug.Log("Failed to read packet data");
            }
        }
        catch (System.NullReferenceException ex)
        {
            Debug.Log($"An error ocurred during parsing some packet data ex: {ex.Message}");
        }
    }
コード例 #21
0
        public LoginModel GetLoginInfo(string username, ResultObject result_object)
        {
            LoginModel _loginModel = new LoginModel();

            try
            {
                using (SqlConnection conn = new SqlConnection(conStr))
                {
                    SqlDataAdapter da = new SqlDataAdapter();
                    DataSet        ds = new DataSet();
                    using (SqlCommand cmd = new SqlCommand("[dbo].[spGetLoginInfo]", conn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@user_name", Convert.ToString(username));
                        cmd.CommandTimeout = 0;
                        conn.Open();
                        da = new SqlDataAdapter(cmd);
                        da.Fill(ds);
                        conn.Close();
                    }
                    if (ds.Tables.Count > 0)
                    {
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            _loginModel.username = Convert.ToString(ds.Tables[0].Rows[0]["user_name"]);
                            _loginModel.userID   = Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"]);
                            _loginModel.name     = Convert.ToString(ds.Tables[0].Rows[0]["name"]);
                            _loginModel.password = Cryptograph.Decrypt(Convert.ToString(ds.Tables[0].Rows[0]["user_password"]));
                            _loginModel.email    = Convert.ToString(ds.Tables[0].Rows[0]["email_id"]);
                            _loginModel.admin    = Convert.ToBoolean(ds.Tables[0].Rows[0]["is_admin"]);
                            //_loginModel.superAdmin = Convert.ToBoolean(ds.Tables[0].Rows[0]["is_super_admin"]);
                            //_loginModel.systemAdmin = Convert.ToBoolean(ds.Tables[0].Rows[0]["is_system_admin"]);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Error.log(ex, "DataAccess.Actions.LoginAction.GetLoginInfo");
                result_object.success         = false;
                result_object.message         = "Unexpected Error occured.Please contact to development team.";
                result_object.is_error_raised = true;
            }
            return(_loginModel);
        }
コード例 #22
0
ファイル: frmPlayVideo.cs プロジェクト: videolib/dotnet
 private void frmPlayVideo_Load(object sender, EventArgs e)
 {
     if (this.NextVideoFileList.Length > 0)
     {
         if (EncryptedVideo)
         {
             string tempDirectory = Path.Combine(Path.GetDirectoryName(this.NextVideoFileList[0]), "Temp");
             System.IO.Directory.CreateDirectory(tempDirectory);
             string tempFilePath = Path.Combine(tempDirectory, Path.GetFileName(this.NextVideoFileList[0]));
             Cryptograph.DecryptFile(this.NextVideoFileList[0], tempFilePath);
             this.axWindowsMediaPlayer1.URL = tempFilePath;
         }
         else
         {
             this.axWindowsMediaPlayer1.URL = this.NextVideoFileList[0];
         }
     }
 }
コード例 #23
0
        /// <summary>Initializes the newly connected client's TCP-related info.</summary>
        /// <param name="_socket">The TcpClient instance of the newly connected client.</param>
        public void Connect(TcpClient _socket)
        {
            socket = _socket;
            socket.ReceiveBufferSize = dataBufferSize;
            socket.SendBufferSize    = dataBufferSize;

            stream = socket.GetStream();

            receivedData  = new Packet();
            receiveBuffer = new byte[dataBufferSize];

            stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);

            PacketHandler.SendPacket(id, ServerPacket.WELCOME, new Dictionary <string, object>()
            {
                { "id", id },
                { "key", Cryptograph.KeyToString(Server.clients[id].clientKeys.publicKey) }
            }, useEncrypt: false);
        }
コード例 #24
0
        private void LoginMethod(PasswordBox pb)
        {
            dbContext = new CinemaContext();
            Password  = pb.Password;
            var password = Cryptograph.Encrypt(Password);
            var user     = dbContext.Users.FirstOrDefault(i => i.Login.ToLower() == this.UserName.ToLower() && i.Password == password);

            if (user == null)
            {
                IncorrectPasswordVisibility = Visibility.Visible;
                PropertyChangedVisibility();
            }
            else
            {
                pb.Password = null;
                CleanAll();
                ParentMainWindowViewModel.Login(user);
            }
        }
コード例 #25
0
ファイル: frmVideoLib - Copy.cs プロジェクト: videolib/dotnet
        private void frmVideoLib_Load(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();
            _clientRootPath     = ConfigHelper.TargetFolderPath;
            _clientInfoFilePath = Path.Combine(_clientRootPath, ConfigHelper.ClientInfoFileName);
            this.ClientInfoObject.LastAccessEndTime   = DateTime.UtcNow;
            this.ClientInfoObject.LastAccessStartTime = DateTime.UtcNow;
            Cryptograph.EncryptObject(this.ClientInfoObject, _clientInfoFilePath);
            //this.lblSchoolName.Text = this.ClientInfoObject.SchoolName;
            this.lblSchoolName.Text = string.Format(this.lblSchoolName.Text, this.ClientInfoObject.SchoolName, this.ClientInfoObject.SchoolId);

            // Fill Tree
            // get root
            string[] rootDirectoryList = Directory.GetDirectories(_clientRootPath);
            for (int i = 0; i < rootDirectoryList.Length; i++)
            {
                TreeNode rootNode = new TreeNode(Path.GetFileName(rootDirectoryList[i]));
                treeView1.Nodes.Add(rootNode);
                AddTreeNode(rootNode, rootDirectoryList[i]);
            }
        }
コード例 #26
0
    public void VerifyUser(int fromClient, Dictionary <string, object> userData)
    {
        int    _clientId = int.Parse(userData["id"].ToString());
        string _username = userData["username"].ToString();
        string _secret   = userData["secret"].ToString();

        try
        {
            if (fromClient != _clientId)
            {
                Debug.Log($"Player \"{_username}\" (ID: {fromClient}) has assumed the wrong client ID ({_clientId})!");
            }
            else
            {
                Server.clients[_clientId].remoteKey = Cryptograph.StringToKey(_secret);

                Debug.Log($"{Server.clients[_clientId].tcp.socket.Client.RemoteEndPoint} connected successfully and is now player {_clientId}.");

                Misc.MakeWebRequest(
                    this,
                    new Action <object, object>((webout, isError) =>
                {
                    if (!(bool)isError)
                    {
                        Server.clients[_clientId].loginHash = webout.ToString();
                    }
                }), new Tuple <string, string>[]
                {
                    new Tuple <string, string>("target", "getHash"),
                    new Tuple <string, string>("username", _username)
                });

                EntityHandler.InstantiateEntity <Player>(_clientId, _username);
            }
        }
        catch (System.NullReferenceException ex)
        {
            Debug.Log($"An error ocurred during parsing some packet data ex: {ex.Message}");
        }
    }
コード例 #27
0
        private void label1_Click(object sender, EventArgs e)
        {
            if (usertxt.Text.Length < 3 || passtxt.Text.Length < 3)
            {
                MessageBox.Show("user or pass no valid ");
            }

            else
            {
                string dir = usertxt.Text;
                if (!Directory.Exists(@"\db" + dir))
                {
                    MessageBox.Show("user not found", "eror");
                }
                else
                {
                    var    sr     = new StreamReader(@"\db" + dir + @"\database.ls");
                    string ecuser = sr.ReadLine();
                    string ecpass = sr.ReadLine();
                    sr.Close();


                    string decuser = Cryptograph.Decrp(ecuser);
                    string decpass = Cryptograph.Decrp(ecpass);

                    if (decuser == usertxt.Text && decpass == passtxt.Text)
                    {
                        sr.Dispose();
                        this.Hide();
                        MainFrm sd = new MainFrm();
                        sd.ShowDialog();
                    }
                    else
                    {
                        MessageBox.Show("Eroor user or pass!");
                    }
                }
            }
        }
コード例 #28
0
ファイル: Program.cs プロジェクト: videolib/dotnet
        private static void OnApplicationExit(object sender, EventArgs e)
        {
            try
            {
                if (CommonAppStateDataHelper.ClientInfoObject.SessionList.Count > 0)
                {
                    int count = CommonAppStateDataHelper.ClientInfoObject.SessionList.Count;
                    CommonAppStateDataHelper.ClientInfoObject.SessionList[count - 1].EndTime = DateTime.Now;
                    CommonAppStateDataHelper.ClientInfoObject.LastAccessEndTime = DateTime.Now;
                    // update it in firebase database.
                    for (int i = 0; i < count; i++)
                    {
                        SaveSessionOnFireBase(CommonAppStateDataHelper.ClientInfoObject.SchoolId,
                                              CommonAppStateDataHelper.ClientInfoObject.SessionList[i].StartTime,
                                              CommonAppStateDataHelper.ClientInfoObject.SessionList[i].EndTime);
                    }

                    CommonAppStateDataHelper.ClientInfoObject.SessionList.Clear();
                    //}
                }
            }
            catch
            {
            }
            finally
            {
                CommonAppStateDataHelper.LoggedIn = false;
                if (CommonAppStateDataHelper.ClientInfoObject != null && CommonAppStateDataHelper.LoggedIn == true && CommonAppStateDataHelper.LicenseError == false)
                {
                    CommonAppStateDataHelper.ClientInfoObject.LastAccessEndTime = DateTime.Now;
                }

                FileInfo clientInfoFileInfo = new FileInfo(ClientHelper.GetClientInfoFilePath());
                clientInfoFileInfo.Attributes &= ~FileAttributes.Hidden;
                Cryptograph.EncryptObject(CommonAppStateDataHelper.ClientInfoObject, ClientHelper.GetClientInfoFilePath());
                clientInfoFileInfo.Attributes |= FileAttributes.Hidden;
            }
        }
コード例 #29
0
        public String SignData(String plainText)
        {
            string message = "";
            //PublicKeyInfrastructure pki = new PublicKeyInfrastructure();
            Cryptograph crypto = new Cryptograph();
            //RSAParameters privateKey = crypto.GenerateKeys("*****@*****.**");
            //RSAParameters publicKey = crypto.GetPublicKey("*****@*****.**");
            //const string PlainText = "This is really sent by me, really!";

            //copied from MSDN article on generating keys
            //Generate a public/private key pair.
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            //Save the public key information to an RSAParameters structure.
            RSAParameters publicKey = RSA.ExportParameters(false);
            RSAParameters privateKey = RSA.ExportParameters(true);

            //This is an interesting exercise in asymmetric encryption, but really isn't
            //needed for signing...
            //string encryptedText = Cryptograph.Encrypt(plainText, publicKey);
            //message += "<br/>This is the encrypted text: " + encryptedText + "<br/>";
            //string decryptedText = Cryptograph.Decrypt(encryptedText, privateKey);
            //message += "<br/>This is the decrypted text: " + decryptedText + "<br/>";
            //string messageToSign = encryptedText;

            string messageToSign = plainText;
            message += "<br/>This is the message: " + messageToSign + "<br/>";

            string signedMessage = Cryptograph.SignData(messageToSign, privateKey);

            message += "<br/>This is the signed message: " + signedMessage + "<br/>";

            //// Is this message really, really, REALLY sent by me?
            bool success = Cryptograph.VerifyData(messageToSign, signedMessage, publicKey);

            message += "<br/>Is this message really, really, REALLY sent by me? " + success;
            return message;
        }
コード例 #30
0
        public void Dispose() //Routine to handle client disposal.
        {
            try
            {
                Terminate();
            }
            catch (Exception ex)
            {
                Log.SkipLine();
                Log.Error("Termination error on {0}: ", ex, Title);
                Log.SkipLine();
            }

            Socket.Dispose();
            Cryptograph.Dispose();
            //ReceiveDone.Dispose(); // TODO: Figure why this crashes.
            ReceivalBuffer.Dispose();

            CustomDispose();

            Unregister();

            Log.Inform("{0} disposed.", Title);
        }
コード例 #31
0
ファイル: frmRegistration.cs プロジェクト: videolib/dotnet
        private void Submit_Click(object sender, EventArgs e)
        {
            string[] oldClientFiles = Directory.GetFiles(_clientTargetPath);
            for (int i = 0; i < oldClientFiles.Length - 1; i++)
            {
                File.Delete(Path.Combine(_clientTargetPath, oldClientFiles[i]));
            }

            // Set client email, password and license date in client info class.
            ClientInfo clientInfo = new ClientInfo();

            clientInfo.EmailId    = txtClientEmail.Text.ToLower().Trim();
            clientInfo.Password   = txtClientPassword.Text.Trim();
            clientInfo.ExpiryDate = TimeZoneInfo.ConvertTime(dtExpiryDate.Value, TimeZoneInfo.Utc);
            clientInfo.SchoolId   = this.txtSchoolId.Text.Trim();
            clientInfo.SchoolName = this.txtSchoolName.Text.Trim();

            // Generate client info json file and encrypt it.
            Cryptograph.EncryptObject(clientInfo, Path.Combine(_clientTargetPath, _clientInfoFileName));

            //  File.Move(_clientInfoFilePath, Path.Combine(_clientTargetPath, Path.GetFileName(_clientInfoFilePath)));

            for (int i = 0; i < chkListBooks.CheckedItems.Count; i++)
            {
                Book selectedBook = (chkListBooks.CheckedItems[i]) as Book;

                string[] selectedBookVideos = Directory.GetFiles(selectedBook.BookId);
                foreach (string selectedBookVideo in selectedBookVideos)
                {
                    string clientTargetVideoPath = Path.Combine(_clientTargetPath, selectedBook.ClassName);

                    clientTargetVideoPath = Path.Combine(clientTargetVideoPath, selectedBook.SeriesName);
                    clientTargetVideoPath = Path.Combine(clientTargetVideoPath, selectedBook.BookName);
                    if (Directory.Exists(clientTargetVideoPath) == false)
                    {
                        Directory.CreateDirectory(clientTargetVideoPath);
                    }
                    clientTargetVideoPath = Path.Combine(clientTargetVideoPath, Path.GetFileName(selectedBookVideo));

                    Cryptograph.EncryptFile(selectedBookVideo, clientTargetVideoPath);
                }
                //string encryptedFilePath = Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath) + "-crypted.mp4");
                //Cryptograph.EncryptFile(filePath, encryptedFilePath);
                //// Copy encrypted files to some target location.
                //File.Copy(encryptedFilePath, Path.Combine(_clientTargetPath, Path.GetFileName(encryptedFilePath)));
            }



            //// Encrypt selected source files.
            //string videoFolderPath = @"D:\School\Videos";
            //foreach (string filePath in Directory.GetFiles(videoFolderPath))
            //{
            //    string encryptedFilePath = Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath) + "-crypted.mp4");
            //    Cryptograph.EncryptFile(filePath, encryptedFilePath);
            //    // Copy encrypted files to some target location.
            //    File.Copy(encryptedFilePath, Path.Combine(_clientTargetPath, Path.GetFileName(encryptedFilePath)));
            //}


            // Copy client project bin folder to target location.
            this.Close();
        }