Exemplo n.º 1
0
        public async Task SendMessage(string userName, string message)
        {
            var key = _keys[Context.ConnectionId];

            var decryptedMessage = AesUtil.Decrypt(message, ((int)key.Key).ToString());

            await Clients.All.SendAsync("Chat", userName, decryptedMessage);
        }
Exemplo n.º 2
0
        private void Button_Click_17(object sender, RoutedEventArgs e)
        {
            byte[] a   = ProtocolUtil.StringToBcd(new SetterDAO().getSetter().Set_Unique_Id);
            byte[] b   = AesUtil.Decrypt(a, ProtocolConstant.USB_DOG_PASSWORD);
            string mac = Encoding.GetEncoding("GBK").GetString(b);

            MessageBox.Show(mac);
        }
Exemplo n.º 3
0
        public void DecryptTest()
        {
            /*
             * AES 以 16 字节为一块,当最后一块不足 16 字节会根据对齐方式补齐,
             * 导致解密后可能和原文相比结尾多出若干个空白字符。
             */

            Assert.Equal(STR_EN, AesUtil.Decrypt("OiGFDP47HdtJxgDbs/KvUQ==", SECRET).TrimEnd('\0'));
            Assert.Equal(STR_CH, AesUtil.Decrypt("eyrfpEEEqwdXvtHoRUF7XgeN49Ug+v7LxMDf/4An0bU=", SECRET).TrimEnd('\0'));
        }
Exemplo n.º 4
0
        public void DecryptTest()
        {
            /*
             * AES �� 16 �ֽ�Ϊһ�飬�����һ�鲻�� 16 �ֽڻ���ݶ��뷽ʽ���룬
             * ���½��ܺ���ܺ�ԭ����Ƚ�β������ɸ��հ��ַ���
             */

            Assert.Equal(STR_EN, AesUtil.Decrypt("OiGFDP47HdtJxgDbs/KvUQ==", SECRET).TrimEnd('\0'));
            Assert.Equal(STR_CH, AesUtil.Decrypt("eyrfpEEEqwdXvtHoRUF7XgeN49Ug+v7LxMDf/4An0bU=", SECRET).TrimEnd('\0'));
        }
Exemplo n.º 5
0
        public void Parser(ref object result, byte[] source)
        {
            //---- 解析逻辑
            //解析出数据体来,赋值给result
            //取出数据长度
            string dataLenStr = source[2].ToString("x2") + source[3].ToString("x2");
            Int32  data_len   = Convert.ToInt32(dataLenStr, 16);

            byte[] temp = new byte[data_len];
            Array.Copy(source, 4, temp, 0, data_len);
            result = AesUtil.Decrypt(temp, ProtocolConstant.USB_DOG_PASSWORD);
        }
Exemplo n.º 6
0
        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            byte[] content = Encoding.ASCII.GetBytes("abcdrfghijklmnopqrstuvwxyz12345678901");

            byte[] jiamihou = AesUtil.Encrypt(content, ProtocolConstant.USB_DOG_PASSWORD);

            var jiemihou = AesUtil.Decrypt(jiamihou, ProtocolConstant.USB_DOG_PASSWORD);

            var str = Encoding.ASCII.GetString(jiemihou);

            MessageBoxX.Info(str);
        }
Exemplo n.º 7
0
        private void DecryptBtn_Click(object sender, RoutedEventArgs e)
        {
            var encryptUtil = new AesUtil(Password.Text, Salt.Text);

            PlainText.Text = encryptUtil.Decrypt(EncryptedText.Text);
        }
Exemplo n.º 8
0
 public ActionResult <string> DecryptAes(string str, string userId)
 {
     return(Ok(AesUtil.Decrypt(str, Guid.Parse(userId))));
 }
Exemplo n.º 9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="uploadManagement">传入上传管理者实体</param>
        /// <returns>返回可以用来上传的辅助对象</returns>
        public ServiceResult GetServiceResult(UploadManagement uploadManagement)
        {
            //service返回结果对象
            ServiceResult serviceResult = new ServiceResult();
            //提前载入唯一Setter
            SetterDAO setterDAO = new SetterDAO();
            Setter    setter    = setterDAO.getSetter();
            //需要加入解密逻辑 TODO
            string mac = "";

            //try
            //{
            //    byte[] deBytes = AesUtil.Decrypt(Encoding.GetEncoding("GBK").GetBytes(setter.Set_Unique_Id),
            //        ProtocolConstant.USB_DOG_PASSWORD);
            //    mac = Encoding.GetEncoding("GBK").GetString(deBytes);
            //}
            //catch (Exception ex)
            //{
            //    mac = setter.Set_Unique_Id.Replace(":", "");
            //}
            byte[] a = ProtocolUtil.StringToBcd(setter.Set_Unique_Id);
            byte[] b = AesUtil.Decrypt(a, ProtocolConstant.USB_DOG_PASSWORD);
            mac = Encoding.GetEncoding("GBK").GetString(b).Replace(":", "-");

            ///if识别出表,设置发送路径,select出实体,转化至DTO,json打成string,返回
            //识别是否是权限用户添加
            if (uploadManagement.UM_DataTable == "bdl_auth")
            {
                AuthDAO authDAO = new AuthDAO();
                Auther  auther  = authDAO.Load(uploadManagement.UM_DataId);
                if (auther == null)
                {
                    return(null);
                }
                AutherDTO autherDTO = new AutherDTO(setter, auther, mac);


                //serviceResult.URL = "clientController/addClient.action";
                serviceResult.Data = JsonTools.Obj2JSONStrNew <AutherDTO>(autherDTO);
            }
            //bdl_customdata表
            else if (uploadManagement.UM_DataTable == "bdl_customdata")
            {
                CustomDataDAO customDataDAO = new CustomDataDAO();
                CustomData    customData    = customDataDAO.Load(uploadManagement.UM_DataId);
                if (customData == null)
                {
                    return(null);
                }
                CustomDataDTO customDataDTO = new CustomDataDTO(customData, mac);
                serviceResult.Data = JsonTools.Obj2JSONStrNew <CustomDataDTO>(customDataDTO);
            }
            //bdl_datacode表
            else if (uploadManagement.UM_DataTable == "bdl_datacode")
            {
                DataCodeDAO dataCodedao = new DataCodeDAO();
                DataCode    dataCode    = dataCodedao.Load(uploadManagement.UM_DataId);

                if (dataCode == null)
                {
                    return(null);
                }
                DataCodeDTO dataCodeDTO = new DataCodeDTO(dataCode, mac);
                serviceResult.Data = JsonTools.Obj2JSONStrNew <DataCodeDTO>(dataCodeDTO);
            }
            //bdl_deviceset表
            else if (uploadManagement.UM_DataTable == "bdl_deviceset")
            {
                DeviceSetDAO deviceSetDAO = new DeviceSetDAO();
                DeviceSet    deviceSet    = deviceSetDAO.Load(uploadManagement.UM_DataId);
                if (deviceSet == null)
                {
                    return(null);
                }
                DeviceSetDTO deviceSetDTO = new DeviceSetDTO(deviceSet, mac);

                serviceResult.Data = JsonTools.Obj2JSONStrNew <DeviceSetDTO>(deviceSetDTO);
            }
            //bdl_devicesort表
            else if (uploadManagement.UM_DataTable == "bdl_devicesort")
            {
                DeviceSortDAO deviceSortDAO = new DeviceSortDAO();
                DeviceSort    deviceSort    = deviceSortDAO.Load(uploadManagement.UM_DataId);
                if (deviceSort == null)
                {
                    return(null);
                }
                DeviceSortDTO deviceSortDTO = new DeviceSortDTO(deviceSort, mac);


                serviceResult.Data = JsonTools.Obj2JSONStrNew <DeviceSortDTO>(deviceSortDTO);
            }
            //bdl_onlinedevice表
            else if (uploadManagement.UM_DataTable == "bdl_onlinedevice")
            {
                OnlineDeviceDAO onlineDeviceDAO = new OnlineDeviceDAO();
                OnlineDevice    onlineDevice    = onlineDeviceDAO.Load(uploadManagement.UM_DataId);

                if (onlineDevice == null)
                {
                    return(null);
                }
                OnlineDeviceDTO onlineDeviceDTO = new OnlineDeviceDTO(onlineDevice, mac);

                serviceResult.Data = JsonTools.Obj2JSONStrNew <OnlineDeviceDTO>(onlineDeviceDTO);
            }
            //bdl_set表
            else if (uploadManagement.UM_DataTable == "bdl_set")
            {
                SetterDAO setterDAO1 = new SetterDAO();
                Setter    setter1    = setterDAO1.Load(uploadManagement.UM_DataId);

                if (setter1 == null)
                {
                    return(null);
                }

                SetterDTO setterDTO = new SetterDTO(setter1, mac);

                serviceResult.Data = JsonTools.Obj2JSONStrNew <SetterDTO>(setterDTO);
            }
            //病人表
            else if (uploadManagement.UM_DataTable == "bdl_user")
            {
                UserDAO userDAO = new UserDAO();
                User    user    = userDAO.Load(uploadManagement.UM_DataId);
                if (user == null)
                {
                    return(null);
                }


                UserDTO userDTO = new UserDTO(user, mac);
                //serviceResult.URL = "bigData/bodyStrongUser";
                serviceResult.Data = JsonTools.Obj2JSONStrNew <UserDTO>(userDTO);
            }

            //症状表
            else if (uploadManagement.UM_DataTable == "bdl_symptominfo")
            {
                SymptomInfoDao symptomInfoDao = new SymptomInfoDao();
                var            result         = symptomInfoDao.Load(uploadManagement.UM_DataId);
                if (result == null)
                {
                    return(null);
                }


                SymptomInfoDTO symptomInfoDTO = new SymptomInfoDTO(result, mac);
                //serviceResult.URL = "bigData/symptomInfo";
                serviceResult.Data = JsonTools.Obj2JSONStrNew <SymptomInfoDTO>(symptomInfoDTO);
            }

            //训练处方总表
            else if (uploadManagement.UM_DataTable == "bdl_traininfo")
            {
                TrainInfoDAO trainInfoDAO = new TrainInfoDAO();
                var          result       = trainInfoDAO.Load(uploadManagement.UM_DataId);
                if (result == null)
                {
                    return(null);
                }


                TrainInfoDTO trainInfoDTO = new TrainInfoDTO(result, mac);
                //serviceResult.URL = "bigData/trainInfo";
                serviceResult.Data = JsonTools.Obj2JSONStrNew <TrainInfoDTO>(trainInfoDTO);
            }

            //总表中的一条数据对某台设备的具体处方
            else if (uploadManagement.UM_DataTable == "bdl_deviceprescription")
            {
                DevicePrescriptionDAO devicePrescriptionDAO = new DevicePrescriptionDAO();
                var result = devicePrescriptionDAO.Load(uploadManagement.UM_DataId);
                if (result == null)
                {
                    return(null);
                }


                DevicePrescriptionDTO devicePrescriptionDTO = new DevicePrescriptionDTO(result, mac);
                //serviceResult.URL = "bigData/devicePrescription";
                serviceResult.Data = JsonTools.Obj2JSONStrNew <DevicePrescriptionDTO>(devicePrescriptionDTO);
            }
            //具体处方的具体反馈
            else if (uploadManagement.UM_DataTable == "bdl_prescriptionresult")
            {
                PrescriptionResultDAO prescriptionResultDAO = new PrescriptionResultDAO();
                var result = prescriptionResultDAO.Load(uploadManagement.UM_DataId);
                if (result == null)
                {
                    return(null);
                }


                PrescriptionResultDTO prescriptionResultDTO = new PrescriptionResultDTO(result, mac);
                //serviceResult.URL = "bigData/prescriptionResult";
                serviceResult.Data = JsonTools.Obj2JSONStrNew <PrescriptionResultDTO>(prescriptionResultDTO);
            }
            else if (uploadManagement.UM_DataTable == "bdl_physicalpower")
            {
                PhysicalPowerDAO physicalPowerDAO = new PhysicalPowerDAO();
                var result = physicalPowerDAO.Load(uploadManagement.UM_DataId);
                if (result == null)
                {
                    return(null);
                }

                PhysicalPowerDTO physicalPowerDTO = new PhysicalPowerDTO(result, mac);
                //serviceResult.URL = "bigData/physicalPower";
                serviceResult.Data = JsonTools.Obj2JSONStrNew <PhysicalPowerDTO>(physicalPowerDTO);
            }
            else if (uploadManagement.UM_DataTable == "bdl_error")
            {
                ErrorDao errorDao = new ErrorDao();
                var      result   = errorDao.Load(uploadManagement.UM_DataId);
                if (result == null)
                {
                    return(null);
                }

                ErrorDTO errorDTO = new ErrorDTO(result, mac);
                //serviceResult.URL = "bigData/physicalPower";
                serviceResult.Data = JsonTools.Obj2JSONStrNew <ErrorDTO>(errorDTO);
            }

            return(serviceResult);
        }
Exemplo n.º 10
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public string Login(string username, string password)
        {
            string  loginResult = "success";
            AuthDAO authDAO     = new AuthDAO();

            //先验证admin
            Auther auther = authDAO.Login(username, password);

            //超管监测权限
            if (auther != null && auther.Auth_Level == Auther.AUTH_LEVEL_ADMIN)
            {
                loginResult = "check_U";
                return(loginResult);
            }
            Auther autherCN = authDAO.GetByName(username);

            //密码错误
            if (autherCN == null)
            {
                loginResult = "没有该用户";
                return(loginResult);
            }

            //没有该用户
            if (autherCN != null && auther == null)
            {
                loginResult = "密码错误!";
                return(loginResult);
            }
            //普通用户测试是否超时登录
            if (auther.Auth_OfflineTime < DateTime.Now)
            {
                loginResult = "您的使用时间已经用尽,请联系宝德龙管理员";
                return(loginResult);
            }


            //登录mac与激活mac不对应
            SetterDAO setterDAO = new SetterDAO();
            Setter    setter    = setterDAO.getSetter();

            string mac = "";

            try {
                byte[] debytes = AesUtil.Decrypt(Encoding.GetEncoding("GBK").GetBytes(setter.Set_Unique_Id), ProtocolConstant.USB_DOG_PASSWORD);

                mac = Encoding.GetEncoding("GBK").GetString(debytes);
                //byte[] a = ProtocolUtil.StringToBcd(setter.Set_Unique_Id);
                //byte[] b = AesUtil.Decrypt(a, ProtocolConstant.USB_DOG_PASSWORD);
                //mac = Encoding.GetEncoding("GBK").GetString(b);
            }
            catch (Exception ex)
            {
                //解密出现问题,经常会报错,目前是直接返回的登陆成功的信息。
                logger.Error("解密异常:" + ex.Message);
                //Console.WriteLine("解密异常:" + ex.Message);
                //loginResult = "解密异常.";
                //return loginResult;
            }
            //如果解密后的setter中的mac不包含现在获得的mac
            if (mac.IndexOf(SystemInfo.GetMacAddress().Replace(":", "-")) == -1)
            {
                //Console.WriteLine("DB:"+ mac);
                //Console.WriteLine("current:" + SystemInfo.GetMacAddress().Replace(":","-"));

                //loginResult = "登录异常";
                //return loginResult;
                logger.Error("机器码匹配异常," + DateTime.Now.ToString());
            }
            if (autherCN.User_Status == Auther.USER_STATUS_FREEZE)
            {
                loginResult = "用户已被冻结";
                return(loginResult);
            }
            return(loginResult);
        }
        /// <summary>
        /// 接收数据的监听方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnPortDataReceived(Object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                Thread.Sleep(50);
                isReceive = true;//收到数据,取消重发

                byte[] buffer = null;;
                int    len    = serialPort.BytesToRead;

                byte[] receiveData = new byte[len];
                serialPort.Read(receiveData, 0, len);
                //Console.WriteLine("收到的数据:" + ProtocolUtil.ByteToStringOk(receiveData));
                int offset = 0;

                Int32 datalen = 0;
                if (len > 0 && receiveData[0] == 0xAA)//第一包数据
                {
                    datalen = Convert.ToInt32((receiveData[2].ToString("X2") + receiveData[3].ToString("X2")), 16);
                    //Console.WriteLine("数据的长度:" + datalen);
                    buffer = new byte[datalen + 6];

                    for (int i = 0; i < receiveData.Length; i++)
                    {
                        buffer[i] = receiveData[i];
                    }
                    offset = receiveData.Length;
                }
                else
                {
                    return;
                }


                while (buffer != null && buffer[buffer.Length - 1] != 0xCC)
                {
                    Thread.Sleep(50);
                    int len2 = serialPort.BytesToRead;

                    if (len2 <= 0)
                    {
                        return;
                    }

                    serialPort.Read(buffer, offset, len2);
                    offset += len2;

                    if (offset > buffer.Length)
                    {
                        return;
                    }
                }

                //下面是完整数据
                if (buffer != null)
                {
                    byte[] data = new byte[datalen + 3];
                    Array.Copy(buffer, 1, data, 0, data.Length);
                    if (buffer[buffer.Length - 2] == ProtocolUtil.XorByByte(data))
                    {
                        object result = null;//用于存放uuid的鉴权加密
                        new ParserUSBDogFrame().Parser(ref result, buffer);
                        string b = ProtocolUtil.BytesToString((byte[])result);
                        //Console.WriteLine("解密通讯加密后的数据:" + b);

                        byte[] uuidBytes = null;
                        uuidBytes = AesUtil.Decrypt((byte[])result, ProtocolConstant.USB_DOG_AUTH_PASSWORD);
                        //Console.WriteLine("解密鉴权加密后的数据:" + ProtocolUtil.ByteToStringOk(uuidBytes));

                        string strUUID = System.Text.Encoding.ASCII.GetString(uuidBytes);

                        if (strUUID == Get_UUID())
                        {
                            //MessageBoxX.Info("激活成功");
                            //todo 全局变量
                            ProtocolConstant.USB_SUCCESS = 1;
                            MessageBoxX.Info(LanguageUtils.ConvertLanguage("激活成功", "Activated successfully"));

                            //Console.WriteLine("激活成功");
                            logger.Debug("激活成功");
                        }
                        else
                        {
                            //MessageBox.Show("激活失败");
                            //Console.WriteLine("激活失败");
                            logger.Debug("激活失败");
                        }
                    }
                    else
                    {
                        //Console.WriteLine("校验失败");
                        logger.Debug("校验失败");
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                //收到消息后至空串口并关闭
                SerialPortUtil.ClosePort(ref serialPort);
                Dispatcher.Invoke(new Action(() =>
                {
                    this.Close();
                }));
            }
        }
        public virtual async Task ImportItem()
        {
            var ext    = $"{new T().ConnectionType.ToString().ToLower()}{ExportFileExtensionSuffix}";
            var dialog = new OpenFileDialog
            {
                FilterIndex     = 1,
                Filter          = $"Connection info files (*.{ext})|*.{ext}",
                Title           = Resources.ConnectionInfo_Dialog_Import_Title,
                CheckFileExists = true,
            };

            if (dialog.ShowDialog() != true)
            {
                return;                              // Break if cancel
            }
            try
            {
                var filename = dialog.FileName;
                MyLogger.Log($"Importing from \"{filename}\"...");

                // Read data from file
                var data = File.ReadAllText(filename);
                // Password input
                var(result, password) = await MainWindow.ShowPasswordInputDialog(
                    Resources.ConnectionInfo_Dialog_Import_PasswordInput_Message,
                    Resources.ConnectionInfo_Dialog_Import_Title,
                    null
                    );

                if (result == false)
                {
                    return;                  // Break if cancel
                }
                var decoded   = Convert.FromBase64String(data);
                var key       = AesUtil.GenerateKeyFromPassword(password);
                var decrypted = AesUtil.Decrypt(decoded, key);
                var info      = ConnectionInfoBase.Deserialize <T>(decrypted);

                EditingItem.Value   = info;
                IsItemEditing.Value = true;

                MyLogger.Log($"Imported \"{info.Name}\" from \"{filename}\".");

                await MainWindow.ShowMessageDialog(
                    string.Format(Resources.ConnectionInfo_Dialog_Import_Imported, filename),
                    Resources.ConnectionInfo_Dialog_Import_Title);
            }
            catch (Exception ex) when(ex is IOException)
            {
                MyLogger.Log($"Failed to import. (IOException", ex);
                await MainWindow.ShowMessageDialog(
                    string.Format(Resources.ConnectionInfo_Dialog_Import_Error_IOException, ex.Message),
                    Resources.ConnectionInfo_Dialog_Import_Title);
            }
            catch (System.Security.Cryptography.CryptographicException ex)
            {
                MyLogger.Log($"Failed to decrypt.", ex);
                await MainWindow.ShowMessageDialog(
                    Resources.ConnectionInfo_Dialog_Import_Error_CryptographicException,
                    Resources.ConnectionInfo_Dialog_Import_Title);
            }
            catch (Exception ex)
            {
                MyLogger.Log($"Failed to import.", ex);
                await MainWindow.ShowMessageDialog(
                    string.Format(Resources.ConnectionInfo_Dialog_Import_Error, ex.Message),
                    Resources.ConnectionInfo_Dialog_Import_Title);
            }
        }