protected override void EndProcessing() { string filePath; if (Path.IsPathRooted(FilePath)) { filePath = Path.GetFullPath(FilePath); } else { filePath = Path.GetFullPath(Path.Join(SessionState.Path.CurrentLocation.Path, FilePath)); } if (!File.Exists(filePath)) { Host.UI.WriteErrorLine($"File does not exist at: {filePath}"); return; } var fileContent = File.ReadAllText(filePath); var dataJson = JObject.Parse(fileContent); string[][] accountArrayHex; if (dataJson.TryGetValue(LocalAccountsUtil.JSON_ENCRYPTED_ACCOUNTS_KEY, out var token)) { if (string.IsNullOrWhiteSpace(Password)) { Host.UI.WriteErrorLine($"No password parameter specified and accounts are encryped in file {FilePath}"); return; } var encrypedAccounts = token.Value <string>(); string decrypedContent; try { decrypedContent = AesUtil.DecryptString(encrypedAccounts, Password); } catch (Exception ex) { Host.UI.WriteErrorLine(ex.ToString()); Host.UI.WriteErrorLine("Failed to decrypt account data. Incorrect password?"); return; } accountArrayHex = JsonConvert.DeserializeObject <string[][]>(decrypedContent); } else { if (!string.IsNullOrWhiteSpace(Password)) { Host.UI.WriteErrorLine($"Password parameter specified but accounts are encryped in file {FilePath}"); return; } accountArrayHex = dataJson[LocalAccountsUtil.JSON_ACCOUNTS_KEY].ToObject <string[][]>(); } var accounts = accountArrayHex .Select(a => EthereumEcdsa.Create(HexUtil.HexToBytes(a[1]), EthereumEcdsaKeyType.Private)) .Select(a => (a.EcdsaKeyPairToAddress(), a)) .ToArray(); GlobalVariables.AccountKeys = accounts; Host.UI.WriteLine($"Loaded {accounts.Length} accounts from {filePath}"); }
private void Btn_Activate(object sender, RoutedEventArgs e) { //InputNonPublicInformationPassword InputNonPublicInformationPassword passwordInput = new InputNonPublicInformationPassword { Owner = Window.GetWindow(this), ShowActivated = true, ShowInTaskbar = false, WindowStartupLocation = WindowStartupLocation.CenterScreen }; passwordInput.ShowDialog(); if (ProtocolConstant.USB_SUCCESS == 0) //u盘成功读取 破解状态为0 { //获取mac地址 StringBuilder stringBuilder = new StringBuilder(); //string strMac = CommUtil.GetMacAddress(); // List<string> Macs = CommUtil.GetMacByWMI(); List <string> Macs = CommUtil.GetMacByIPConfig(); foreach (string mac in Macs) { string prefix = "物理地址. . . . . . . . . . . . . : "; string Mac = mac.Substring(prefix.Length - 1); stringBuilder.Append(Mac); } //Console.WriteLine("==================="+stringBuilder.ToString()); //MessageBox.Show("===================" + stringBuilder.ToString()); entity.Setter setter = new entity.Setter(); //mac地址先变为byte[]再aes加密 byte[] byteMac = Encoding.GetEncoding("GBK").GetBytes(stringBuilder.ToString()); byte[] AesMac = AesUtil.Encrypt(byteMac, ProtocolConstant.USB_DOG_PASSWORD); //存入数据库 //setter.Set_Unique_Id = Encoding.GetEncoding("GBK").GetString(AesMac); setter.Set_Unique_Id = ProtocolUtil.BytesToString(AesMac); /*AES解密 * byte[] a = ProtocolUtil.StringToBcd(setter.Set_Unique_Id); * byte[] b = AesUtil.Decrypt(a, ProtocolConstant.USB_DOG_PASSWORD); * Console.WriteLine(Encoding.GetEncoding("GBK").GetString(b));*/ //默认照片路径,激活时获取(路径中不要有汉字) string basePath = System.AppDomain.CurrentDomain.BaseDirectory; string path = ConfigurationManager.AppSettings["PicPath"]; setter.Set_PhotoLocation = basePath + path; setter.Set_Language = 1; //默认备份路径,激活时获取 setter.Back_Up = basePath + @"BackUp\"; setter.Set_Language = 1; //设置版本号 setter.Set_Version = CommUtil.GetCurrentVersion(); if (!Directory.Exists(@setter.Set_PhotoLocation)) { Directory.CreateDirectory(@setter.Set_PhotoLocation);//不存在就创建目录 } /*if (Directory.Exists(@setter.Set_PhotoLocation)) { //存在就删除 * Directory.Delete(@setter.Set_PhotoLocation, true); * Directory.CreateDirectory(@setter.Set_PhotoLocation); * }*/ SetterDAO.InsertOneMacAdress(setter); //注释的部分为添加多个mac地址 // List<entity.Setter> ListMac = CommUtil.GetMacByWMI(); // SetterDAO.InsertMacAdress(ListMac); Status.Content = LanguageUtils.GetCurrentLanuageStrByKey("SettingsView.Activated"); Color color = Color.FromArgb(255, 2, 200, 5); Status.Foreground = new SolidColorBrush(color); BtnActivite.IsEnabled = false; } else { MessageBoxX.Error(LanguageUtils.ConvertLanguage("激活失败", "Activation fails")); } }
internal static string EncryptDateAndCount(DateTime date, int count, string pass) { var s = date.ToString("yyyy/MM/dd") + "#" + count.ToString(); return(AesUtil.EncryptString(s, pass)); }
protected override void EndProcessing() { if (GlobalVariables.AccountKeys == null || GlobalVariables.AccountKeys.Length == 0) { Host.UI.WriteErrorLine($"No accounts are loaded. Use '{CmdLetExtensions.GetCmdletName<NewAccountsCommand>()}' to generate accounts."); return; } string filePath; if (Path.IsPathRooted(FilePath)) { filePath = Path.GetFullPath(FilePath); } else { filePath = Path.GetFullPath(Path.Join(SessionState.Path.CurrentLocation.Path, FilePath)); } if (EncryptData && string.IsNullOrWhiteSpace(Password)) { Host.UI.WriteErrorLine($"No '{nameof(Password)}' parameter is provided. To write without encryption set the '{nameof(EncryptData)}' parameter to false"); return; } if (!string.IsNullOrWhiteSpace(Password) && !EncryptData) { Host.UI.WriteErrorLine($"The '{nameof(EncryptData)}' parameter is set to false but the '{nameof(Password)}' parameter is provided. Pick one."); return; } var accounts = GlobalVariables.AccountKeys; var accountArrayHex = accounts .Select(a => new[] { a.Address.ToString(hexPrefix: true), HexUtil.GetHexFromBytes(a.Account.ToPrivateKeyArray(), hexPrefix: true) }) .ToArray(); JObject dataObj = new JObject(); if (EncryptData) { var accountJson = JsonConvert.SerializeObject(accountArrayHex, Formatting.Indented); var encrypedAccountsString = AesUtil.EncryptString(accountJson, Password); dataObj[LocalAccountsUtil.JSON_ENCRYPTED_ACCOUNTS_KEY] = encrypedAccountsString; } else { dataObj[LocalAccountsUtil.JSON_ACCOUNTS_KEY] = JArray.FromObject(accountArrayHex); } if (File.Exists(filePath)) { var choices = new Collection <ChoiceDescription>(new[] { new ChoiceDescription("Cancel"), new ChoiceDescription("Overwrite") }); var overwrite = Host.UI.PromptForChoice($"File already exists at {filePath}", "Continue and overwite existing file?", choices, 0); if (overwrite != 1) { Host.UI.WriteErrorLine("Accounts not saved to file."); return; } } var dataJson = dataObj.ToString(Formatting.Indented); File.WriteAllText(filePath, dataJson); if (EncryptData) { Host.UI.WriteLine($"Wrote {accounts.Length} encrypted accounts to: {filePath}"); } else { Host.UI.WriteLine($"Wrote {accounts.Length} unencrypted accounts to: {filePath}"); } }
// ======================================== // static method // ======================================== internal static string EncryptBoolAndVersion(bool b, Version version, string pass) { var s = b.ToString() + "#" + version.ToString(); return(AesUtil.EncryptString(s, pass)); }
/// <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); }
public static void BuildIOS() { //string luaCompilerPath = PlayerPrefs.GetString( "luac_path" ); string luaCompilerPath = PlayerPrefs.GetString("luajit_path"); string luaPath = PlayerPrefs.GetString("lua_path"); DirectoryInfo di = new DirectoryInfo(luaCompilerPath); if (string.IsNullOrEmpty(luaCompilerPath) || !di.Exists) { throw new Exception("Luajit path not exist."); } di = new DirectoryInfo(luaPath); if (string.IsNullOrEmpty(luaPath) || !di.Exists) { throw new Exception("Lua path not exist."); } //md5 Hashtable md5Map; string v = luaPath + "/ver.txt"; if (File.Exists(v)) { string vJson = File.ReadAllText(v); md5Map = ( Hashtable )MiniJSON.JsonDecode(vJson); } else { md5Map = new Hashtable(); } FileInfo[] fis = di.GetFiles("*.lua", SearchOption.AllDirectories); foreach (FileInfo fi in fis) { string md5Digest = MD5Util.GetMd5HexDigest(fi); string subPath = fi.DirectoryName.Replace(luaPath, string.Empty); string toPath = Application.dataPath + "/Sources/Lua" + subPath; string destName = fi.Name.Replace(".lua", ".bytes"); string dest = toPath + "/" + destName; string key = subPath + "/" + fi.Name; if (md5Map.ContainsKey(key) && ( string )md5Map[key] == md5Digest && File.Exists(dest)) { continue; } md5Map[key] = md5Digest; if (!Directory.Exists(toPath)) { Directory.CreateDirectory(toPath); } string text = File.ReadAllText(fi.FullName); byte[] bytes = Encoding.UTF8.GetBytes(text); bytes = AesUtil.AesEncrypt(bytes); File.WriteAllBytes(dest, bytes); } AssetDatabase.Refresh(); List <string> assets = new List <string>(); string assetPath = Application.dataPath + "/Sources/Lua"; DirectoryInfo di2 = new DirectoryInfo(assetPath); DirectoryInfo[] di2S = di2.GetDirectories(); foreach (DirectoryInfo di3 in di2S) { assets.Add("Assets/Sources/Lua/" + di3.Name); } FileInfo[] fi2S = di2.GetFiles(); foreach (FileInfo fi2 in fi2S) { if (fi2.Extension == ".bytes") { assets.Add("Assets/Sources/Lua/" + fi2.Name); } } for (int i = 0; i < assets.Count; i++) { string assetPath2 = assets[i]; WriteAssetBundleName(assetPath2, "lua"); } AssetDatabase.Refresh(); string nv = MiniJSON.JsonEncode(md5Map); File.WriteAllText(v, nv); }
/// <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); } }