void recvParam() { CryptoTool ct = new CryptoTool(); var blockData = ct.cbc_decode(Request.Form["blockData"]); var kv = JsonConvert.DeserializeObject <Dictionary <string, string> >(blockData); this.id = kv["id"]; this.uid = kv["uid"]; this.pid = kv["pid"]; // this.perSvr = kv["perSvr"]; //文件百分比 this.lenSvr = kv["lenSvr"]; //已传大小 this.lenLoc = kv["lenLoc"]; //本地文件大小 this.nameLoc = kv["nameLoc"]; // this.sizeLoc = kv["sizeLoc"]; // this.blockOffset = kv["blockOffset"]; this.blockIndex = kv["blockIndex"]; //块偏移,相对于文件 this.blockCount = kv["blockCount"]; //块总数 this.blockSize = kv["blockSize"]; //块大小 this.blockSizeLogic = kv["blockSizeLogic"]; //逻辑块大小(定义的块大小) this.blockMd5 = kv["blockMd5"]; //块MD5 this.pathLoc = kv["pathLoc"]; // this.pathSvr = kv["pathSvr"]; this.pathRel = kv["pathRel"]; this.pidRoot = kv["pidRoot"];//文件夹标识(guid) this.pathLoc = PathTool.url_decode(this.pathLoc); this.nameLoc = PathTool.url_decode(this.nameLoc); this.pathSvr = PathTool.url_decode(this.pathSvr); this.pathRel = PathTool.url_decode(this.pathRel); }
/// <summary> /// Constructor /// </summary> /// <param name="algorithm"></param> /// <param name="key"></param> public SymmetricEncryptor(SymmetricAlgorithm algorithm, string key) { algorithm.ShouldNotBeNull("algorithm"); key.ShouldNotBeEmpty("key"); //if(algorithm.GetType().Equals(typeof(RijndaelManaged))) // throw new NotSupportedException("RijndaelManaged 알고리즘은 지원하지 않습니다. TripleDESCryptoServiceProvider를 사용하시기 바랍니다."); Algorithm = algorithm; Key = key; var newLength = Algorithm.KeySize / 8; Algorithm.Key = CryptoTool.DerivePassword(Key, newLength); if (algorithm is Rijndael) { Algorithm.BlockSize = Algorithm.KeySize; } if (IsDebugEnabled) { log.Debug("대칭형 암호화를 수행하는 SymmectricEncryptor를 생성했습니다. Algorithm=[{0}], KeySize=[{1}], BlockSize=[{2}]", Algorithm, Algorithm.KeySize, Algorithm.BlockSize); } }
/// <summary> /// /// </summary> /// <param name="mail"></param> /// <param name="password"></param> /// <returns></returns> public async Task <long> CreateUser(string mail, string password, string telegram, string skype) { skype = skype?.Trim(); telegram = TelegramFormatter.ReplaceRussiaToWorldCode(telegram); _logger.LogTrace($"Call CreateUser({mail}, ***, {telegram}, {skype})"); if (!UserContactsValidator.IsValid(skype, telegram)) { _logger.LogInformation($"Invalid contacts: [telegram: {telegram} ], [skype: {skype} ]"); throw new InvalidRegistrationDataException(); } var salt = CryptoTool.CreateSalt(); var passwordHash = CryptoTool.Hash(password, salt); var newUser = new User { Mail = mail, PasswordSalt = Convert.ToBase64String(salt), PasswordHash = passwordHash, RegisterDate = DateTime.Now }; const string queryStringInsertUser = @" INSERT INTO users (mail, password_hash, password_salt) VALUES (@Mail, @PasswordHash, @PasswordSalt) ON CONFLICT DO NOTHING RETURNING id "; var response = await _connection.QueryAsync <long>(queryStringInsertUser, newUser); var newId = response.SingleOrDefault(); if (newId == 0) { throw new UserAlreadyExistsException(); } newUser.Id = newId; const string queryStringProfile = @" INSERT INTO user_profiles (user_id) VALUES (@Id); "; await _connection.QueryAsync(queryStringProfile, newUser); const string queryStringPayment = @" INSERT INTO user_payments_info (user_id) VALUES (@Id); "; await _connection.QueryAsync(queryStringPayment, newUser); List <UserContact> contacts = FillContacts(newId, skype, telegram); await AddContacts(contacts); return(newId); }
private Kullanici KullaniciGetir(GirisModel model) { var pass = CryptoTool.EnCryptoPass(model.Sifre); IQueryable <Kullanici> query = _queryable.Table; return(query.Include(s => s.KullaniciRolleri.Select(w => w.Rol)).FirstOrDefault(s => s.KullaniciAdi == model.KullaniciAdi && s.KullaniciSifreleri.Any(e => e.Sifre == pass && !s.Silindi) && !s.Silindi)); }
/// <summary> /// <see cref="Key"/>값을 변경합니다. /// </summary> private void SetupKey() { if (Key == null) { Key = CryptoTool.DerivePassword(Password, 32); KeySize = Key.Length * 8; } }
private string DecryptString(string encryptedData) { string decrypted; CryptoTool Crypto = new CryptoTool(); decrypted = Crypto.DefaultDecrypt(encryptedData); return(decrypted); }
public string ComputePassword(Guid id, string login, string password) { var salt = CryptoTool.EncryptMD5(EncodingTool.UCS2.GetBytes($"{id.ToString().Substring(0, 8)}{id.ToString().Substring(23, 12)}")); var hash = EncodingTool.UTF8.GetBytes(login).Concat(salt).Concat(EncodingTool.UTF16.GetBytes(password)); var result = EncodingTool.UTF8.GetString(CryptoTool.EncryptSha256(hash)); return(result); }
private void btnGenerateKeys_Click(object sender, EventArgs e) { CryptoTool crypt = new CryptoTool(); // Generate 10 keys by default for (var x = 0; x < 10; x++) { EncryptionKeys key = new EncryptionKeys(); key.Password = crypt.CreatePassSalt(256); key.Salt = crypt.CreatePassSalt(15); key.XorKey = crypt.CreateXOR_Pass(Rando.GetNumber(256).ToString()); // instead of a username we'll just use int for XOR key // We'll leave the VI alone ClientConfig.EncryptionKeys.Add(key); // Add to client key list } }
/// <summary> /// 지정한 정보를 암호화한다. /// </summary> /// <param name="plainBytes">암호화할 정보</param> /// <returns>암호화된 정보</returns> public byte[] Encrypt(byte[] plainBytes) { plainBytes.ShouldNotBeEmpty("plainBytes"); if (IsDebugEnabled) { log.Debug("지정된 바이트 배열에 대해 암호화를 진행합니다... Algorithm=[{0}], keySize=[{1}]", Algorithm, Algorithm.KeySize); } var ivBytes = CryptoTool.GetInitialVector(Algorithm.KeySize); var keyBytes = Algorithm.Key; // CryptoUtils.DerivePassword(Key, Algorithm.KeySize / 8); using (var transform = Algorithm.CreateEncryptor(keyBytes, ivBytes)) { return(transform.TransformFinalBlock(plainBytes, 0, plainBytes.Length)); } }
/// <summary> /// 难证token /// </summary> /// <param name="token"></param> /// <param name="f"></param> /// <param name="action">动作:init,block</param> /// <returns></returns> public bool validToken(string token, FileInf f, string action = "init") { ConfigReader cr = new ConfigReader(); var sec = cr.module("path"); var encrypt = (bool)sec.SelectToken("$.security.token"); if (encrypt) { if (string.IsNullOrEmpty(token.Trim())) { return(false); } CryptoTool ct = new CryptoTool(); return(ct.token(f, action) == token); } return(true); }
protected void Page_Load(object sender, EventArgs e) { string id = this.reqString("id"); string pid = this.reqString("pid"); string pidRoot = this.reqString("pidRoot"); string uid = this.reqString("uid"); string lenLoc = this.reqString("lenLoc"); string sizeLoc = this.reqString("sizeLoc"); string pathLoc = this.reqStringDecode("pathLoc"); string callback = this.reqString("callback");//jsonp参数 if (string.IsNullOrEmpty(pid)) { pid = string.Empty; } if (string.IsNullOrEmpty(pidRoot)) { pidRoot = pid; } if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(uid) || string.IsNullOrEmpty(pathLoc) ) { Response.Write(callback + "({\"value\":null})"); return; } FileInf fileSvr = new FileInf(); fileSvr.id = id; fileSvr.pid = pid; fileSvr.pidRoot = pidRoot; fileSvr.fdChild = false; fileSvr.fdTask = true; fileSvr.uid = int.Parse(uid);//将当前文件UID设置为当前用户UID fileSvr.nameLoc = Path.GetFileName(pathLoc); fileSvr.pathLoc = pathLoc; fileSvr.lenLoc = Convert.ToInt64(lenLoc); fileSvr.sizeLoc = sizeLoc; fileSvr.deleted = false; fileSvr.nameSvr = fileSvr.nameLoc; //生成存储路径 PathBuilderUuid pb = new PathBuilderUuid(); fileSvr.pathSvr = pb.genFolder(ref fileSvr); fileSvr.pathSvr = fileSvr.pathSvr.Replace("\\", "/"); if (!Directory.Exists(fileSvr.pathSvr)) { Directory.CreateDirectory(fileSvr.pathSvr); } //添加成根目录 if (string.IsNullOrEmpty(pid)) { DBConfig cfg = new DBConfig(); DBFile db = cfg.db(); db.Add(ref fileSvr); }//添加成子目录 else { DBConfig cfg = new DBConfig(); SqlExec se = cfg.se(); se.insert("up6_folders", new SqlParam[] { new SqlParam("f_id", fileSvr.id) , new SqlParam("f_nameLoc", fileSvr.nameLoc) , new SqlParam("f_pid", fileSvr.pid) , new SqlParam("f_pidRoot", fileSvr.pidRoot) , new SqlParam("f_lenLoc", fileSvr.lenLoc) , new SqlParam("f_sizeLoc", fileSvr.sizeLoc) , new SqlParam("f_pathLoc", fileSvr.pathLoc) , new SqlParam("f_pathSvr", fileSvr.pathSvr) , new SqlParam("f_uid", fileSvr.uid) }); } //加密 ConfigReader cr = new ConfigReader(); var sec = cr.module("path"); var encrypt = (bool)sec.SelectToken("$.security.encrypt"); if (encrypt) { CryptoTool ct = new CryptoTool(); fileSvr.pathSvr = ct.encode(fileSvr.pathSvr); } up6_biz_event.folder_create(fileSvr); string json = JsonConvert.SerializeObject(fileSvr); json = HttpUtility.UrlEncode(json); json = json.Replace("+", "%20"); var jo = new JObject { { "value", json } }; json = callback + string.Format("({0})", JsonConvert.SerializeObject(jo)); this.toContentJson(json); }
void fd_create() { string id = Request.QueryString["id"]; string pid = Request.QueryString["pid"]; string uid = Request.QueryString["uid"]; string lenLoc = Request.QueryString["lenLoc"]; string sizeLoc = Request.QueryString["sizeLoc"]; string pathLoc = HttpUtility.UrlDecode(Request.QueryString["pathLoc"]); string pathRel = this.reqString("pathRel"); string callback = Request.QueryString["callback"];//jsonp参数 if (string.IsNullOrEmpty(pid)) { pid = string.Empty; } pid = pid.Trim(); if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(uid) || string.IsNullOrEmpty(pathLoc) ) { Response.Write(callback + "({\"value\":null})"); return; } FileInf fileSvr = new FileInf(); fileSvr.id = id; fileSvr.pid = pid; fileSvr.pidRoot = ""; fileSvr.fdChild = false; fileSvr.fdTask = true; fileSvr.uid = int.Parse(uid);//将当前文件UID设置为当前用户UID fileSvr.nameLoc = Path.GetFileName(pathLoc); fileSvr.pathLoc = pathLoc; fileSvr.pathRel = PathTool.combin(pathRel, fileSvr.nameLoc); fileSvr.lenLoc = Convert.ToInt64(lenLoc); fileSvr.sizeLoc = sizeLoc; fileSvr.deleted = false; fileSvr.nameSvr = fileSvr.nameLoc; //检查同名目录 //DbFolder df = new DbFolder(); //if (df.exist_same_folder(fileSvr.nameLoc, pid)) //{ // var o = new JObject { { "value", null }, { "ret", false }, { "code", "102" } }; // var js = callback + string.Format("({0})", JsonConvert.SerializeObject(o)); // this.toContent(js); // return; //} //生成存储路径 PathBuilderUuid pb = new PathBuilderUuid(); fileSvr.pathSvr = pb.genFolder(ref fileSvr); fileSvr.pathSvr = fileSvr.pathSvr.Replace("\\", "/"); if (!Directory.Exists(fileSvr.pathSvr)) { Directory.CreateDirectory(fileSvr.pathSvr); } //添加成根目录 if (string.IsNullOrEmpty(pid)) { DBConfig cfg = new DBConfig(); DBFile db = cfg.db(); db.Add(ref fileSvr); }//添加成子目录 else { DBConfig cfg = new DBConfig(); SqlExec se = cfg.se(); se.insert("up6_folders", new SqlParam[] { new SqlParam("f_id", fileSvr.id) , new SqlParam("f_nameLoc", fileSvr.nameLoc) , new SqlParam("f_pid", fileSvr.pid) , new SqlParam("f_pidRoot", "") , new SqlParam("f_lenLoc", fileSvr.lenLoc) , new SqlParam("f_sizeLoc", fileSvr.sizeLoc) , new SqlParam("f_pathLoc", fileSvr.pathLoc) , new SqlParam("f_pathSvr", fileSvr.pathSvr) , new SqlParam("f_pathRel", fileSvr.pathRel) , new SqlParam("f_uid", fileSvr.uid) }); } //加密 ConfigReader cr = new ConfigReader(); var sec = cr.module("path"); var encrypt = (bool)sec.SelectToken("$.security.encrypt"); if (encrypt) { CryptoTool ct = new CryptoTool(); fileSvr.pathSvr = ct.encode(fileSvr.pathSvr); } up6_biz_event.folder_create(fileSvr); string json = JsonConvert.SerializeObject(fileSvr); json = HttpUtility.UrlEncode(json); json = json.Replace("+", "%20"); var jo = new JObject { { "value", json }, { "ret", true } }; json = callback + string.Format("({0})", JsonConvert.SerializeObject(jo)); this.toContent(json); }
/// <summary> /// 只负责拼接文件块。将接收的文件块数据写入到文件中。 /// 更新记录: /// 2012-04-12 更新文件大小变量类型,增加对2G以上文件的支持。 /// 2012-04-18 取消更新文件上传进度信息逻辑。 /// 2012-10-30 增加更新文件进度功能。 /// 2015-03-19 文件路径由客户端提供,此页面不再查询文件在服务端的路径。减少一次数据库访问操作。 /// 2016-03-31 增加文件夹信息字段 /// 2017-07-11 优化参数检查逻辑 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { string uid = this.headString("uid"); string f_id = this.headString("id"); string lenSvr = this.headString("lenSvr"); //已传大小 string lenLoc = this.headString("lenLoc"); //本地文件大小 string blockOffset = this.headString("blockOffset"); string blockSize = this.headString("blockSize"); //当前块大小 string blockIndex = this.headString("blockIndex"); //当前块索引,基于1 string blockMd5 = this.headString("blockMd5"); //块MD5 string complete = this.headString("complete"); //true/false string pathSvr = Request.Form["pathSvr"]; // string pathLoc = string.Empty; string token = this.headString("token"); // pathSvr = Server.UrlDecode(pathSvr); if (!this.safe_check(lenLoc, uid, f_id, blockOffset, pathSvr)) { return; } //有文件块数据 if (Request.Files.Count > 0) { bool verify = false; string msg = string.Empty; string md5Svr = string.Empty; HttpPostedFile file = Request.Files.Get(0);//文件块 var stm = file.InputStream; var stmLen = int.Parse(blockSize); pathLoc = file.FileName; //加密 ConfigReader cr = new ConfigReader(); var sec = cr.module("path"); var encrypt = (bool)sec.SelectToken("$.security.encrypt"); if (encrypt) { CryptoTool ct = new CryptoTool(); pathSvr = ct.decode(pathSvr); stm = ct.decode(file.InputStream, int.Parse(blockSize)); } //token验证 WebSafe ws = new WebSafe(); FileInf fileSvr = new FileInf(); fileSvr.id = f_id; fileSvr.pathLoc = file.FileName; fileSvr.pathSvr = pathSvr; FileInfo fi = new FileInfo(pathLoc); fileSvr.nameLoc = fi.Name; verify = ws.validToken(token, fileSvr, "block"); //token验证失败 if (!verify) { msg = string.Format("token error loc:{0}", token); } //计算文件块MD5 if (!string.IsNullOrEmpty(blockMd5)) { md5Svr = Md5Tool.calc(stm); } //文件块大小验证 if (verify) { verify = int.Parse(blockSize) == stm.Length; } if (!verify) { msg = "block size error sizeSvr:" + stm.Length + " sizeLoc:" + blockSize; } //块MD5验证 if (verify && !string.IsNullOrEmpty(blockMd5)) { verify = md5Svr == blockMd5; if (!verify) { msg = "block md5 error"; } } if (verify) { PathBuilder pb = new PathBuilder(); pathSvr = pb.relToAbs(pathSvr); //2.0保存文件块数据 FileBlockWriter res = new FileBlockWriter(); res.make(pathSvr, Convert.ToInt64(lenLoc)); res.write(pathSvr, Convert.ToInt64(blockOffset), stm); up6_biz_event.file_post_block(f_id, Convert.ToInt32(blockIndex)); //生成信息 JObject o = new JObject(); o["msg"] = "ok"; o["md5"] = md5Svr; //文件块MD5 o["offset"] = blockOffset; //偏移 msg = JsonConvert.SerializeObject(o); } this.toContentJson(msg); } }
protected void Page_Load(object sender, EventArgs e) { string op = this.reqString("op"); string pid = this.reqString("pid"); string pidRoot = this.reqString("pidRoot"); string md5 = this.reqString("md5"); string id = this.reqString("id"); string uid = this.reqString("uid"); string lenLoc = this.reqString("lenLoc"); string sizeLoc = this.reqString("sizeLoc"); string token = this.reqString("token"); string callback = this.reqString("callback"); //jsonp参数 //客户端使用的是encodeURIComponent编码, string pathLoc = this.reqStringDecode("pathLoc"); //utf-8解码 if (op == "mkpath") { this.mkpath(); } if (string.IsNullOrEmpty(pid)) { pid = string.Empty; } if (string.IsNullOrEmpty(pidRoot)) { pidRoot = pid; } //参数为空 if (string.IsNullOrEmpty(md5) || string.IsNullOrEmpty(uid) || string.IsNullOrEmpty(sizeLoc) ) { Response.Write(callback + "({\"value\":null})"); return; } FileInf fileSvr = new FileInf(); fileSvr.fdChild = false; fileSvr.uid = int.Parse(uid);//将当前文件UID设置为当前用户UID fileSvr.id = id; fileSvr.pid = pid; fileSvr.fdChild = !string.IsNullOrEmpty(pid); fileSvr.pidRoot = pidRoot; fileSvr.nameLoc = Path.GetFileName(pathLoc); fileSvr.pathLoc = pathLoc; fileSvr.lenLoc = Convert.ToInt64(lenLoc); fileSvr.sizeLoc = sizeLoc; fileSvr.deleted = false; fileSvr.md5 = md5; fileSvr.nameSvr = fileSvr.nameLoc; WebSafe ws = new WebSafe(); var ret = ws.validToken(token, fileSvr); //token验证失败 if (!ret) { string m = callback + "({\"value\":\"0\",\"ret\":false,\"msg\":\"token error\"})";//返回jsonp格式数据。 this.toContentJson(m); return; } //所有单个文件均以uuid/file方式存储 PathBuilderUuid pb = new PathBuilderUuid(); fileSvr.pathSvr = pb.genFile(fileSvr.uid, ref fileSvr); fileSvr.pathSvr = fileSvr.pathSvr.Replace("\\", "/"); //数据库存在相同文件 DBConfig cfg = new DBConfig(); DBFile db = cfg.db(); FileInf fileExist = new FileInf(); if (db.exist_file(md5, ref fileExist)) { fileSvr.nameSvr = fileExist.nameSvr; fileSvr.pathSvr = fileExist.pathSvr; fileSvr.perSvr = fileExist.perSvr; fileSvr.lenSvr = fileExist.lenSvr; fileSvr.complete = fileExist.complete; db.Add(ref fileSvr); //触发事件 up6_biz_event.file_create_same(fileSvr); }//数据库不存在相同文件 else { db.Add(ref fileSvr); //触发事件 up6_biz_event.file_create(fileSvr); //2.0创建器。仅创建一个空白文件 FileBlockWriter fr = new FileBlockWriter(); fr.make(fileSvr.pathSvr, fileSvr.lenLoc); } //将路径转换成相对路径 fileSvr.pathSvr = pb.absToRel(fileSvr.pathSvr); //加密 ConfigReader cr = new ConfigReader(); var sec = cr.module("path"); var encrypt = (bool)sec.SelectToken("$.security.encrypt"); if (encrypt) { CryptoTool ct = new CryptoTool(); fileSvr.pathSvr = ct.encode(fileSvr.pathSvr); } string jv = JsonConvert.SerializeObject(fileSvr); jv = HttpUtility.UrlEncode(jv); jv = jv.Replace("+", "%20"); string json = callback + "({\"value\":\"" + jv + "\",\"ret\":true})";//返回jsonp格式数据。 this.toContentJson(json); }
static Keychain() { mCryptoInstance = new CryptoTool("oPXJN744LGH5v2pX3BVj", "KlUiCgYcoHBzB8sjYA4z"); }
void f_create() { string pid = Request.QueryString["pid"]; string pidRoot = Request.QueryString["pidRoot"]; string md5 = Request.QueryString["md5"]; string id = Request.QueryString["id"]; string uid = Request.QueryString["uid"]; string lenLoc = Request.QueryString["lenLoc"]; string sizeLoc = Request.QueryString["sizeLoc"]; string callback = Request.QueryString["callback"]; //jsonp参数 //客户端使用的是encodeURIComponent编码, string pathLoc = HttpUtility.UrlDecode(Request.QueryString["pathLoc"]); //utf-8解码 string pathRel = this.reqString("pathRel"); if (string.IsNullOrEmpty(pid)) { pid = string.Empty; } if (string.IsNullOrEmpty(pidRoot)) { pidRoot = pid; } //参数为空 if (string.IsNullOrEmpty(md5) || string.IsNullOrEmpty(uid) || string.IsNullOrEmpty(sizeLoc)) { Response.Write(callback + "({\"value\":null})"); return; } FileInf fileSvr = new FileInf(); fileSvr.fdChild = false; fileSvr.uid = int.Parse(uid);//将当前文件UID设置为当前用户UID fileSvr.id = id; fileSvr.pid = pid; fileSvr.fdChild = !string.IsNullOrEmpty(pid); fileSvr.pidRoot = pidRoot; fileSvr.nameLoc = Path.GetFileName(pathLoc); fileSvr.pathLoc = pathLoc; fileSvr.pathRel = PathTool.combin(pathRel, fileSvr.nameLoc); fileSvr.lenLoc = Convert.ToInt64(lenLoc); fileSvr.sizeLoc = sizeLoc; fileSvr.deleted = false; fileSvr.md5 = md5; fileSvr.nameSvr = fileSvr.nameLoc; //同名文件检测 //DbFolder df = new DbFolder(); //if (df.exist_same_file(fileSvr.nameLoc, pid)) //{ // var data = callback + "({'value':'','ret':false,'code':'101'})"; // this.toContent(data); // return; //} //所有单个文件均以uuid/file方式存储 PathBuilderUuid pb = new PathBuilderUuid(); fileSvr.pathSvr = pb.genFile(fileSvr.uid, ref fileSvr); fileSvr.pathSvr = fileSvr.pathSvr.Replace("\\", "/"); //数据库存在相同文件 DBConfig cfg = new DBConfig(); DBFile db = cfg.db(); FileInf fileExist = new FileInf(); if (db.exist_file(md5, ref fileExist)) { fileSvr.nameSvr = fileExist.nameSvr; fileSvr.pathSvr = fileExist.pathSvr; fileSvr.perSvr = fileExist.perSvr; fileSvr.lenSvr = fileExist.lenSvr; fileSvr.complete = fileExist.complete; db.Add(ref fileSvr); //触发事件 up6_biz_event.file_create_same(fileSvr); }//数据库不存在相同文件 else { db.Add(ref fileSvr); //触发事件 up6_biz_event.file_create(fileSvr); //2.0创建器。仅创建一个空白文件 FileBlockWriter fr = new FileBlockWriter(); fr.make(fileSvr.pathSvr, fileSvr.lenLoc); } //加密 ConfigReader cr = new ConfigReader(); var sec = cr.module("path"); var encrypt = (bool)sec.SelectToken("$.security.encrypt"); if (encrypt) { CryptoTool ct = new CryptoTool(); fileSvr.pathSvr = ct.encode(fileSvr.pathSvr); } string jv = JsonConvert.SerializeObject(fileSvr); jv = HttpUtility.UrlEncode(jv); jv = jv.Replace("+", "%20"); string json = callback + "({\"value\":\"" + jv + "\",\"ret\":true})";//返回jsonp格式数据。 this.toContent(json); }
// Creates a new thread per connection from this function // This function is the actual communication with the specific connection private void StartSlave() { CryptoTool crypto = new CryptoTool(); //---Slave master list creation and assignment---\\ Slave client = new Slave(); client.AssignedKeys = false; client.ConnectionKey = ClientConfig.connectionKey; if (clientConnection.Connected) { client.OnlineStatus = OnlineInfo.Online; // Assign online } else { client.OnlineStatus = OnlineInfo.Offline; // Assign offline } client.Authorized = false; //---Local variable creation---\\ bool Authing = true; bool Authed = false; bool KeepAlive = true; int AuthStep = 1; int clientListNumber = 0; // make it 0 so we can handle things better int bytesRead = 0; // Byte count from stream read string dataReceived; // string of byte data recieved byte[] dataSent; // Byte data to send to client - probly wont be used NetworkStream nwStream = clientConnection.GetStream(); // Start connection stream byte[] buffer = new byte[clientConnection.ReceiveBufferSize]; // SslStream slStream = new SslStream(nwStream); // Iniate stream for future use // Mess with secure encrypted stream stuff later // SslStream sStream = new SslStream(nwStream); try { while (KeepAlive) // keep looping while we tell it to { if (!Authed & Authing) { //---read incoming stream---\\ bytesRead = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize); //---convert the data received into a string---\\ dataReceived = crypto.DefaultDecrypt(Encoding.ASCII.GetString(buffer, 0, bytesRead)); // Decrypt data to string WorkQueue.AddBytes(buffer.Length); if (ClientConfig.Debug) { Logger.SaveDebug("==================START OF NEW CLIENT VERIFICATION================"); } if (ClientConfig.Debug) { Logger.SaveDebug($"NEW CLIENT! | ID: {dataReceived} - AUTH SEQUENCE STARTED!"); } Debug.WriteLine("Step 0 - Received : " + dataReceived); client.ClientID = dataReceived; ClientHandler.AddClient(client); client.SlaveListAssignment = ClientHandler.AssignClientListCount(client.ClientID); clientListNumber = client.SlaveListAssignment; if (clientListNumber == 0) { // Issue handling the list number assignment code //TODO: What/how do we handle this? } //---Sending acknowledge---\\ dataSent = null; dataSent = Encoding.ASCII.GetBytes(crypto.DefaultEncrypt("VALID")); // encrypt to send WorkQueue.AddBytes(dataSent.Length); nwStream.Write(dataSent, 0, dataSent.Length); Debug.WriteLine("Telling client step 0 valid..."); dataSent = null; bytesRead = 0; //---Auth sequence loop handling until pass or failure---\\ while (Authing & AuthStep != 0) { ClientAuth auth = new ClientAuth(); if (String.IsNullOrWhiteSpace(ClientHandler.Slaves[clientListNumber].IP)) { ClientHandler.Slaves[clientListNumber].IP = auth.GetIP(dataReceived); } //using (AuthSteps step = new AuthSteps()) //{ switch (AuthStep) { case 1: // Read response bytesRead = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize); WorkQueue.AddBytes(buffer.Length); dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead); Debug.WriteLine("Step 1 - Received : " + dataReceived); if (ClientConfig.Debug) { Logger.SaveDebug($"Step 1 started for client {ClientHandler.Slaves[clientListNumber].ClientID}"); } if (auth.CheckAuth(crypto.DefaultDecrypt(dataReceived), 1)) { AuthStep = 2; //---sending back valid step 1---\\ dataSent = null; dataSent = Encoding.ASCII.GetBytes(crypto.DefaultEncrypt("VALID")); nwStream.Write(dataSent, 0, dataSent.Length); WorkQueue.AddBytes(dataSent.Length); Debug.WriteLine("Telling client step 1 valid..."); dataSent = null; ClientHandler.Slaves[clientListNumber].AuthStatus.Step1Done = true; if (ClientConfig.Debug) { Logger.SaveDebug($"Step 1 verified | client {ClientHandler.Slaves[clientListNumber].ClientID}"); } } else { Logger.SaveDebug($"Step 1 FAILED! for client {ClientHandler.Slaves[clientListNumber].ClientID}"); AuthStep = 0; // Deny Authing = false; Authed = false; clientConnection.Close(); if (ClientConfig.Debug) { Logger.SaveDebug($"Client disconnected and slave list updated for client!"); } ClientHandler.Slaves[clientListNumber].Authorized = false; ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.BadLogin; } break; case 2: // Read response bytesRead = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize); dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead); WorkQueue.AddBytes(buffer.Length); Debug.WriteLine("Step 2 - Received : " + dataReceived); if (ClientConfig.Debug) { Logger.SaveDebug($"Step 2 started for client {ClientHandler.Slaves[clientListNumber].ClientID}"); } // Process response if (auth.CheckAuth(crypto.DefaultDecrypt(dataReceived), 2)) { dataSent = null; AuthStep = 3; dataSent = Encoding.ASCII.GetBytes(crypto.DefaultEncrypt("VALID")); nwStream.Write(dataSent, 0, dataSent.Length); WorkQueue.AddBytes(dataSent.Length); Debug.WriteLine("Telling client step 2 valid..."); dataSent = null; ClientHandler.Slaves[clientListNumber].AuthStatus.Step2Done = true; if (ClientConfig.Debug) { Logger.SaveDebug($"Step 2 VALID for client {ClientHandler.Slaves[clientListNumber].ClientID}"); } } else { AuthStep = 0; // Deny Authing = false; Authed = false; clientConnection.Close(); ClientHandler.Slaves[clientListNumber].Authorized = false; ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.BadLogin; if (ClientConfig.Debug) { Logger.SaveDebug($"Step 2 FAILED | closed connection and updated slave list."); } } break; case 3: // Read response //bytesRead = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize); //dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead); //Debug.WriteLine("Step 3 - Received : " + dataReceived); if (ClientConfig.Debug) { Logger.SaveDebug($"Step 3 started for client {ClientHandler.Slaves[clientListNumber].ClientID}"); } // Process response if (ClientConfig.AssignNewKeys) { dataSent = null; EncryptionKeys newKeys = ClientConfig.EncryptionKeys[Rando.GetNumber(ClientConfig.EncryptionKeys.Count)]; ClientHandler.Slaves[clientListNumber].key = newKeys; dataSent = Encoding.ASCII.GetBytes(crypto.DefaultEncrypt($"KEYS:{newKeys.Password}:{newKeys.Salt}:{newKeys.XorKey}:{newKeys.VlKey}")); nwStream.Write(dataSent, 0, dataSent.Length); WorkQueue.AddBytes(dataSent.Length); ClientHandler.Slaves[clientListNumber].AuthStatus.Step3Done = true; ClientHandler.Slaves[clientListNumber].Authorized = true; if (ClientConfig.Debug) { Logger.SaveDebug($"Step 3 COMPLETED for client {ClientHandler.Slaves[clientListNumber].ClientID}"); } bytesRead = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize); dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead); WorkQueue.AddBytes(buffer.Length); if (dataReceived.Contains("UPDATED")) { Authed = true; Authing = false; } else { // Bad sequence sent, close connection AuthStep = 0; // Deny Authing = false; Authed = false; clientConnection.Close(); ClientHandler.Slaves[clientListNumber].Authorized = false; ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.Unknown; if (ClientConfig.Debug) { Logger.SaveDebug($"Step 3 FAILED | Connection closed and list updated | ERROR UPDATING KEYS!"); } } } else { // Bad sequence sent, close connection AuthStep = 0; // Deny Authing = false; Authed = false; clientConnection.Close(); ClientHandler.Slaves[clientListNumber].Authorized = false; ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.VMDenied; if (ClientConfig.Debug) { Logger.SaveDebug($"Step 3 FAILED | Connection closed and list updated"); } } break; default: // Bad sequence sent, close connection AuthStep = 0; // Deny Authing = false; Authed = false; clientConnection.Close(); ClientHandler.Slaves[clientListNumber].Authorized = false; ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.Error; if (ClientConfig.Debug) { Logger.SaveDebug($"Default auth switch hit, ERROR occured!"); } break; } //} } // Authing loop Debug.WriteLine($"Auth Status processed: {Authed} | Auth sequence processing is complete"); } else if (Authed & !Authing) // Process this after client has been authorized { // read response //bytesRead = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize); //dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead); // Send response //dataSent = null; //dataSent = Encoding.ASCII.GetBytes(crypto.DefaultEncrypt("VALID")); //nwStream.Write(dataSent, 0, dataSent.Length); for (var x = 0; x < WorkQueue.JobQueue.Count; x++) { if (WorkQueue.JobQueue[x] != null) // Validate we haven't grabbed a junk list item { if (WorkQueue.JobQueue[x].ClientID == ClientHandler.Slaves[clientListNumber].ClientID & !WorkQueue.JobQueue[x].Sent) // Client has work in queue that isn't sent yet { // Pending work, let's send it switch (WorkQueue.JobQueue[x].WorkType) { case WorkType.Kill: default: if (ClientConfig.Debug) { Logger.SaveDebug($"JobQueue item {x} could not be handled for client {WorkQueue.JobQueue[x].ClientID}({ClientHandler.Slaves[clientListNumber].ClientID})"); } Debug.WriteLine($"JobQueue item {x} could not be handled for client {WorkQueue.JobQueue[x].ClientID}({ClientHandler.Slaves[clientListNumber].ClientID})"); break; } } } } } else { // Unknown not authed or not failed to auth either KeepAlive = false; } }// end of keepalive loop ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.Offline; Debug.WriteLine("KEEP ALIVE OFF AND SLAVE THREAD ENDING!"); Logger.SaveDebug("KEEP ALIVE OFF AND SLAVE THREAD ENDING!"); } catch (Exception ex) { ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.Offline; Debug.WriteLine("ERROR! >> " + ex); } }