public string DecryptEncrypt(string str, Crypt crypt) { checkIsStringCorrect(str); string result = ""; foreach (char t in str) { if (t == ' ') { result += ' '; continue; } for (int j = 0; j < _charletters.Length; j++) { if (t == _charletters[j]) { if (crypt== Crypt.Decrypt) { result += (j - _offset < 0) ? _charletters[_charletters.Length - j - _offset] : _charletters[j - _offset]; } else { result += (j + _offset < _charletters.Length) ? _charletters[j + _offset] : _charletters[j + _offset - _charletters.Length]; } break; } } } return result; }
public conData_MYSQL() { m_DataSource = ""; m_DataBase = ""; m_UserName = ""; m_crypted_Password = ""; m_Crypt = new Crypt(encrypt_num); }
//public string m_WindowsAuthentication_UserName = SystemInformation.UserDomainName + "\\" + SystemInformation.UserName; public conData_MYSQL(string xDataSource, string xDataBase, string xUserName, string xcrypted_Password) { m_DataSource = xDataSource; m_DataBase = xDataBase; m_UserName = xUserName; m_crypted_Password = xcrypted_Password; m_Crypt = new Crypt(encrypt_num); }
public conData_MSSQL() { m_DataSource = ""; m_DataBase = ""; m_UserName = ""; m_crypted_Password = ""; m_bWindowsAuthentication = false; m_strDataBaseFilePath = ""; m_strDataBaseLogFilePath = ""; m_Crypt = new Crypt(encrypt_num); m_TryToConnectTimeout_in_seconds = 60; }
public conData_MSSQL( bool xbWindowsAuthentication, string xDataSource, string xDataBase, string xUserName, string x_crypted_Password, string xstrDataBaseFilePath, string xstrDataBaseLogFilePath, int xTryToConnectTimeout_in_seconds) { m_DataSource = xDataSource; m_DataBase = xDataBase; m_UserName = xUserName; m_crypted_Password = x_crypted_Password; m_bWindowsAuthentication = xbWindowsAuthentication; m_strDataBaseFilePath = xstrDataBaseFilePath; m_strDataBaseLogFilePath = xstrDataBaseLogFilePath; m_Crypt = new Crypt(encrypt_num); m_TryToConnectTimeout_in_seconds = xTryToConnectTimeout_in_seconds; }
public override void DeleteFiles(string domain, List <string> paths) { if (paths == null) { throw new ArgumentNullException("paths"); } foreach (var path in paths) { var target = GetTarget(domain, path); if (!File.Exists(target)) { continue; } var size = Crypt.GetFileSize(target); File.Delete(target); QuotaUsedDelete(domain, size); } }
public void EncryptDecryptTest() { var secret = Crypt.NewSecret(); var plain = new byte[] { 1, 2, 3 }; var cipher = Crypt.Encrypt(secret, plain); Assert.That(cipher.Count(), Is.GreaterThan(3)); Assert.That(cipher, Is.Not.EquivalentTo(plain)); var decrypted = Crypt.Decrypt(secret, cipher); Assert.That(decrypted, Is.EquivalentTo(plain)); var secret2 = Crypt.NewSecret(secret.Key); var cipher2 = Crypt.Encrypt(secret2, plain); Assert.That(cipher2.Count(), Is.GreaterThan(3)); Assert.That(cipher, Is.Not.EquivalentTo(plain)); Assert.That(cipher2, Is.Not.EquivalentTo(cipher)); var decrypted2 = Crypt.Decrypt(secret2, cipher2); Assert.That(decrypted2, Is.EquivalentTo(plain)); }
/// <summary> /// Получение таблицы с параметрами соединения источника данных дешифрованным паролем /// </summary> /// <param name="src">таблица - рез-т выполнения функции 'GetConnectionSettings'</param> /// <param name="row_src"></param> /// <param name="psw"></param> /// <param name="row_psw"></param> /// <returns></returns> private static DataTable GetConnectionSettings(ref DataTable src, int row_src, ref DataTable psw, int row_psw) { string errMsg, strPsw; errMsg = strPsw = string.Empty; if (psw.Rows.Count == 1) { //hash = psw.Rows[row_psw]["HASH"].ToString ().ToCharArray (); //len_hash = psw.Rows[row_psw]["HASH"].ToString().Length; strPsw = Crypt.Crypting().Decrypt(psw.Rows[row_psw]["HASH"].ToString(), Crypt.KEY); } else { ; } //Проверка с каким вариантом БД происходит работа if (src.Columns.IndexOf("PASSWORD") < 0) { src.Columns.Add("PASSWORD", typeof(string)); } else { ; } if (row_src < src.Rows.Count) { src.Rows[row_src]["PASSWORD"] = strPsw; } else { ; } return(src); }
public void Update(MPerson value) { _XDoc = new XmlDocument(); _Stream = new FileStream(_FilePath, FileMode.Open); _XDoc.Load(_Stream); XmlNodeList list = _XDoc.GetElementsByTagName(_SubName); for (int i = 0; i < list.Count; i++) { XmlElement cl = (XmlElement)_XDoc.GetElementsByTagName(_SubName)[i]; if (value.Id.Equals(cl.GetAttribute("Id"))) { cl.SetAttribute("VName", Crypt.EncryptString(value.VName, value.Id)); cl.SetAttribute("NName", Crypt.EncryptString(value.NName, value.Id)); cl.SetAttribute("Mid", Crypt.EncryptString(value.Mid, value.Id)); cl.SetAttribute("TaughtNr", value.TaughtNr); break; } } _Stream.Close(); _XDoc.Save(_FilePath); }
public ActionResult Activate(ActivateModel model) { string token; try { // Get the token from the RouteData token = SqlInjection.SafeSqlLiteral(Url.RequestContext.RouteData.Values["id"].ToString()); } // ReSharper disable EmptyGeneralCatchClause catch (Exception) // ReSharper restore EmptyGeneralCatchClause { return(RedirectToAction("Index", "Home")); } if (String.IsNullOrEmpty(token) || token.Length != 32) { return(RedirectToAction("Index", "Home")); } // Load in values from database model.GetValues(token); // Make Postal code upperCase, remove spaces and encrypt the string model.PostalCode = Crypt.StringEncrypt( SqlInjection.SafeSqlLiteral(StringManipulation.ToUpperFast(model.PostalCode)) .Replace(" ", string.Empty), model.Pepper); model.HouseNumber = Crypt.StringEncrypt(SqlInjection.SafeSqlLiteral(model.HouseNumber), model.Pepper); // If UpdateAccount fails show error page if (!model.UpdateAccount()) { return(View("Error")); } // Make cookie for user Cookies.MakeCookie(model.Mail, model.Id.ToString(CultureInfo.InvariantCulture), "0"); return(RedirectToAction("Account", "Logged")); }
public void Parse(ArkCompareOptions op) { var ark1 = ArkFile.FromFile(op.ArkPath1); var ark2 = ArkFile.FromFile(op.ArkPath2); var ark1Entries = ark1.Entries .Select(x => x as OffsetArkEntry) .Select(x => new { Name = x.FullPath, x.Size, Hash = Crypt.SHA1Hash(ark1.GetArkEntryFileStream(x)) }) .ToList(); var ark2Entries = ark2.Entries .Select(x => x as OffsetArkEntry) .Select(x => new { Name = x.FullPath, x.Size, Hash = Crypt.SHA1Hash(ark1.GetArkEntryFileStream(x)) }) .ToList(); var sharedEntries = ark1Entries .Intersect(ark2Entries) .ToList(); var ark1UniqueEntries = ark1Entries .Except(sharedEntries) .ToList(); var ark2UniqueEntries = ark2Entries .Except(sharedEntries) .ToList(); // TODO: Create formatted console output }
/// <summary> /// 保存配置文件 /// </summary> public void SaveParam() { DataRow dr; if (drs != null && drs.Length == 0) { dr = dt.NewRow(); //增加一个新行 } else { dr = drs[0]; } dr[0] = dataIndex.ToString(); dr[1] = Crypt.Encrypt(strServerName); //验证方式 if (loginModel_flag) { dr[2] = "Y"; } else { dr[2] = "N"; } dr[3] = Crypt.Encrypt(user); dr[4] = Crypt.Encrypt(passID); dr[5] = Crypt.Encrypt(data_source); if (drs != null && drs.Length == 0) { dt.Rows.Add(dr); } dt.AcceptChanges(); dt.WriteXml(strPath); //把配置写入XML文件 }
//���[�U���X�g�̏����� private void Init(IEnumerable <OneDat> datUser) { _ar.Clear(); if (datUser != null) { foreach (var o in datUser) { if (!o.Enable) { continue; //�L���ȃf�[�^������Ώۂɂ��� } var name = o.StrList[0]; var pass = Crypt.Decrypt(o.StrList[1]); _ar.Add(new OneMailBox(name, pass)); var folder = string.Format("{0}\\{1}", Dir, name); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } } } }
//Добавление сотрудника public void Employee_Insert(string Employee_Surname, string Employee_Name, string Employee_Middle_Name, string Login, string Password, bool Logical_Delete, int Role_ID, string Passport_Series, string Passport_Number, int Post_ID, string Contract_Date) { int contractID; //Создание трудового договора commandConfig("Contract_Insert"); command.Parameters.AddWithValue("@Passport_Series", Passport_Series); command.Parameters.AddWithValue("@Passport_Number", Passport_Number); command.Parameters.AddWithValue("@Post_ID", Post_ID); command.Parameters.AddWithValue("@Contract_Date", Contract_Date); DBConnection.connection.Open(); command.ExecuteNonQuery(); DBConnection.connection.Close(); //Получает id контракта command.CommandType = System.Data.CommandType.Text; command.CommandText = "SELECT MAX(ID_Contract) FROM [Contract]"; DBConnection.connection.Open(); contractID = Convert.ToInt32(command.ExecuteScalar().ToString()); command.ExecuteNonQuery(); DBConnection.connection.Close(); //Создание записи о сотрудники //Шифрование string passwordEnc = Crypt.Encrypt(Password); commandConfig("Employee_Insert"); command.Parameters.AddWithValue("@Employee_Surname", Employee_Surname); command.Parameters.AddWithValue("@Employee_Name", Employee_Name); command.Parameters.AddWithValue("@Employee_Middle_Name", Employee_Middle_Name); command.Parameters.AddWithValue("@Login", Login); command.Parameters.AddWithValue("@Password", passwordEnc); command.Parameters.AddWithValue("@Logical_Delete", Logical_Delete); command.Parameters.AddWithValue("@Role_ID", Role_ID); command.Parameters.AddWithValue("@Contract_ID", contractID); DBConnection.connection.Open(); command.ExecuteNonQuery(); DBConnection.connection.Close(); }
/// <summary> /// To be called at the end of OnPreRender(): /// Persist the in this page life-cycle stage immutable Main object. /// </summary> /// <typeparam name="M"></typeparam> /// <param name="controlStorage"></param> public static void SaveMain <M>(this IStorageControl <M> controlStorage) where M : class, new() { var storage = controlStorage.GetStorage(); Trace.Assert(controlStorage.Main != null, "SaveMain() without preceding LoadMain()"); switch (storage) { case Storage.ViewState: controlStorage.ViewState[controlStorage.StorageID()] = controlStorage.Main; break; case Storage.Session: controlStorage.Session[controlStorage.StorageID()] = controlStorage.Main; break; case Storage.Database: Guid session = Guid.NewGuid(); // cannot exist in the database -> will get a new one on SaveMain() var cookie = controlStorage.Request.Cookies[controlStorage.StorageID()]; if (cookie != null) { Guid.TryParse(controlStorage.Request.Cookies[controlStorage.StorageID()]["session"], out session); } Func <byte[], byte[]> filter = null; if (controlStorage.GetEncryptDatabaseStorage()) { filter = x => Crypt.Encrypt(controlStorage.GetSecret(), x); // closure } session = Main.SaveMain(controlStorage.Main, session, filter); var configDays = ConfigurationManager.AppSettings["DatabaseStorageExpires"]; var days = String.IsNullOrWhiteSpace(configDays) ? 1 : int.Parse(configDays); controlStorage.Response.Cookies[controlStorage.StorageID()]["session"] = session.ToString(); controlStorage.Response.Cookies[controlStorage.StorageID()].Expires = DateTime.Now.AddDays(days); break; } }
public override Uri Move(string srcdomain, string srcpath, string newdomain, string newpath) { if (srcpath == null) { throw new ArgumentNullException("srcpath"); } if (newpath == null) { throw new ArgumentNullException("srcpath"); } var target = GetTarget(srcdomain, srcpath); var newtarget = GetTarget(newdomain, newpath); if (File.Exists(target)) { if (!Directory.Exists(Path.GetDirectoryName(newtarget))) { Directory.CreateDirectory(Path.GetDirectoryName(newtarget)); } var flength = Crypt.GetFileSize(target); //Delete file if exists if (File.Exists(newtarget)) { File.Delete(newtarget); } File.Move(target, newtarget); QuotaUsedDelete(srcdomain, flength); QuotaUsedAdd(newdomain, flength); } else { throw new FileNotFoundException("File not found", Path.GetFullPath(target)); } return(GetUri(newdomain, newpath)); }
/// <summary> /// Lista todos os pedidos feitos pelo cliente /// </summary> /// <returns></returns> public ActionResult Index() { HttpCookie cookie = (HttpCookie)Request.Cookies["usuario"]; if (cookie.Values.AllKeys[0] == null) { return(RedirectToAction("LogOn", "Account")); } String usuarioId = Crypt.Decrypter(cookie.Values.AllKeys[0]); ObjectResult <SP_GetPedido_Result> result = null; result = _pedidosDao.getAllPedidos(usuarioId, ""); _pedido = new List <SP_GetPedido>(); if (result != null) { foreach (var item in result) { SP_GetPedido ped = new SP_GetPedido(); ped.pednum = item.pednum; ped.dtcad = String.Format("{0:dd/MM/yyyy}", item.dtcad); ped.vlrPedido = String.Format("{0:#,0.00}", item.vlrpedido); ped.idstaPedido = item.idsta; ped.idsta = GetManutencaoPedido.statusConsultaPedido(item.idsta); ped.totitem = (int)item.totitem; ped.frete = item.frete; // ped.dtprventrega = String.Format("{0:dd/MM/yyyy}", item.dtprventrega); ped.dtprventrega = getNumerodeDias(item.dtcad, item.dtprventrega).ToString(); _pedido.Add(ped); } } ViewBag.Tema = Settings.Default.Tema; return(View(_pedido)); }
private void frm_main_btn_gerar_Click(object sender, EventArgs e) { if (frm_main_tb_site.Text.Equals("") || frm_main_tb_validade.Text.Equals("") || frm_main_tb_qtd_user.Text.Equals("") || frm_main_tb_contrato.Text.Equals("")) { MessageBox.Show("Todos os campos devem ser preenchidos!", "Atenção..."); } else { //DateTime dataValidade; StringBuilder stringBuilder = new StringBuilder(frm_main_tb_sys.Text); stringBuilder.Append(frm_main_tb_site.Text); stringBuilder.Append(frm_main_tb_validade.Text); stringBuilder.Append(frm_main_tb_qtd_user.Text.PadLeft(5, '0')); stringBuilder.Append(frm_main_tb_contrato.Text.PadLeft(10, '0')); //stringBuilder.Append(frm_main_tb_validade.Text.ToString("ddMMyyyy")); string chave = frm_main_tb_sys.Text + frm_main_tb_site.Text; Crypt crypt = new Crypt(CryptProvider.RC2, chave); frm_main_tb_licenca.Text = stringBuilder.ToString(); try { frm_main_tb_licenca.Text = crypt.Encrypt(stringBuilder.ToString()); frm_main_btn_copiar.Enabled = true; //frm_main_btn_gerar.Enabled = false; frm_main_tb_licenca.Enabled = true; frm_main_tb_licenca.ForeColor = System.Drawing.Color.Green; } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
public async Task <Int32Result> FeltoltesAngular([FromQuery] string sid, [FromBody] FajlBuf par) { var result = new Int32Result(); using (var tr = await _context.Database.BeginTransactionAsync()) try { par.Hash = Crypt.MD5Hash(par.b); // a kliensen kellene készíteni... par.Ext = Path.GetExtension(par.Fajlnev); if (string.IsNullOrEmpty(par.Megjegyzes)) { par.Megjegyzes = Path.GetFileNameWithoutExtension(par.Fajlnev); } var entityDokumentum = await DokumentumBll.BejegyzesAsync(_context, sid, par); tr.Commit(); try { DokumentumBll.BejegyzesFajl(entityDokumentum); DokumentumBll.FeltoltesFajl(entityDokumentum, par); result.Result = entityDokumentum.Dokumentumkod; } catch (Exception ef) { result.Error = ef.InmostMessage(); } } catch (Exception ex) { tr.Rollback(); result.Error = ex.InmostMessage(); } return(result); }
public JsonResult update_blog() { try { Crypt cr = new Crypt(); HomeModel HM = new HomeModel(); string decryptedCookie_serialized = Request.Form["serialized_cookie"]; cr.EncryptionKey = HM.getEncryptionKey(); string DecryptedCookie = cr.Decrypt(decryptedCookie_serialized); string brief = Request.Form["brief"]; string content = Request.Form["content"]; Dictionary <string, string> user = JsonConvert.DeserializeObject <Dictionary <string, string> >(DecryptedCookie); string uid = user["uid"]; return(Json(HM.update_blog(brief, content, uid))); } catch (Exception ex) { throw ex; } }
public IActionResult Registration([FromBody] UsersVM userVm) { if (string.IsNullOrEmpty(userVm.Login) || string.IsNullOrEmpty(userVm.Password)) { return(Ok(new { success = false, message = "Недопустимый формат" })); } var user = new Users { Login = userVm.Login, Password = Crypt.GenerateHashPassword(userVm.Password), Address = userVm.Address, Email = userVm.Email, Full_name = userVm.Full_name, Phone = userVm.Phone, Money = 0, Token = Crypt.GenerateToken(userVm.Login) }; _userRepository.Add(user); return(Ok(new { success = true, message = "Пользователь зарегистрирован", token = user.Token })); }
public ActionResult Autenticacao(usuario usuario) { using (sbk101dbEntities db = new sbk101dbEntities()) { usuario.senha = Crypt.Hash(usuario.senha); var usuarioDetalhe = db.usuario.Where(x => x.login == usuario.login && x.senha == usuario.senha).FirstOrDefault(); if (usuarioDetalhe == null) { usuario.LoginErrorMessage = "Dados Inválidos"; return(View("Login", usuario)); } else { Session["UserId"] = usuarioDetalhe.id; Session["UserName"] = usuarioDetalhe.nome; if (usuarioDetalhe.admin == true) { Session["UserAdmin"] = usuarioDetalhe.admin; } return(RedirectToAction("Index", "Home")); } } }
/// <summary> /// Авторизация /// </summary> /// <param name="login">Логин</param> /// <param name="password">Пароль</param> /// <returns>id пользователя</returns> public int Authorization(string login, string password) { string passwordEnc = Crypt.Encrypt(password); //Зашифрованный пароль try { command.CommandType = System.Data.CommandType.Text; command.CommandText = "select [IDPersonalCard] from [dbo].[PersonalCard] " + "where [Login] = '" + login + "' and [Password] = '" + passwordEnc + "'"; DBConnection.connection.Open(); idUser = Convert.ToInt32(command.ExecuteScalar().ToString()); return(idUser); } catch { idUser = 0; return(idUser); } finally { connection.Close(); } }
public override void Load(Stream stream) { try { using (StreamReader reader = new StreamReader(stream)) { string json = reader.ReadToEnd(); var data = JsonConvert.DeserializeObject <IDictionary <string, string> >(json); foreach (var key in data.Keys.ToArray()) { try { data[key] = Crypt.DecryptString(data[key], Cipher); } catch (Exception ex) { Core.Log.Error($"Error decrypting data\n{ex}"); } } Data = data; } } catch (Exception ex) { Core.Log.Debug($"Failed to load protected configuration.\n{ex}"); } }
/// <summary> /// Allows the player to change their password. /// </summary> /// <param name="oldPassword">The old password that they used</param> /// <param name="newPassword">The new password that they want to use</param> /// <returns></returns> public bool ChangePassword(string oldPassword, string newPassword) { // If the current hash password equals the oldpassword passed in. if (Crypt.CrypCompare(Password, Crypt.GenerateSaltedHash(oldPassword, Salt))) { if (!String.IsNullOrEmpty(newPassword)) { Salt = Crypt.GenerateSalt(newPassword.Length); Password = Crypt.GenerateSaltedHash(newPassword, Salt); return(true); } else { SendMessage("The new password was blank, please re-enter."); return(false); } } else { SendMessage("Failed to update password, password entered doesn't match records."); return(false); } }
private string GenCheckMacValue(Dictionary <string, string> postCollection) { string _newQuery = "", _newQuery2 = ""; if (postCollection.Count > 0) { foreach (KeyValuePair <string, string> item in postCollection) { _newQuery += HttpUtility.UrlDecode(item.Key + "=" + item.Value + "&"); } _newQuery2 = _newQuery.Substring(0, _newQuery.Length - 1); } //beta測試 //_newQuery = string.Format("HashKey={0}&{1}&HashIV={2}", "WC4O2h6oOKqY3Vuk", _newQuery2, "75UnvoWg1BKArQ14"); //dev測試 _newQuery = string.Format("HashKey={0}&{1}&HashIV={2}", "hk64SbkO9teN7GTC", _newQuery2, "N1HqECaW8GrTPsDs"); _newQuery = HttpUtility.UrlEncode(_newQuery).ToLower(); string MacValue = new Crypt().MD5(_newQuery); return(MacValue); }
/// <summary> /// Check HDD serial number with serial numbers database /// </summary> /// <returns>Returns true if hwid checking fails</returns> private static bool CheckHWID(string diskLetter) { string line; GetVolumeInformation(diskLetter, sb_volume_name, (UInt32)sb_volume_name.Capacity, ref serial_number, ref max_component_length, ref file_system_flags, sb_file_system_name, (UInt32)sb_file_system_name.Capacity); using (WebClient web = new WebClient()) { using (StringReader reader = new StringReader(web.DownloadString(Crypt.Decode("aHR0cDovL3p1cnJhcGEuaG9zdC9Zek5XYVdOMw")))) { while ((line = reader.ReadLine()) != null) { if (!line.StartsWith("/") && Crypt.Decode(line).Equals(serial_number.ToString())) { return(false); } } } } return(true); }
public ActionResult FindKey(HttpPostedFileBase file, string text) { if (file == null && text.Length < 1) { return(RedirectToAction("FindKey")); } text = GetNeededText(file, text); if (text == null) { return(RedirectToAction("FindKey")); } string fileName = file?.FileName ?? "Noname.txt"; int[] keys = Crypt.GetKeys(text); string[] texts = keys.Select(key => Crypt.Decryption(key, text)).ToArray(); ViewBag.FileName = fileName; ViewBag.Keys = keys; ViewBag.Texts = texts; return(View("~/Views/Result/FindKey.cshtml")); }
public override void DeleteDirectory(string domain, string path) { if (path == null) { throw new ArgumentNullException("path"); } //Return dirs var targetDir = GetTarget(domain, path); if (string.IsNullOrEmpty(targetDir)) { throw new Exception("targetDir is null"); } if (!string.IsNullOrEmpty(targetDir) && !targetDir.EndsWith(Path.DirectorySeparatorChar.ToString())) { targetDir += Path.DirectorySeparatorChar; } if (!Directory.Exists(targetDir)) { return; } var entries = Directory.GetFiles(targetDir, "*.*", SearchOption.AllDirectories); var size = entries.Select(entry => Crypt.GetFileSize(entry)).Sum(); var subDirs = Directory.GetDirectories(targetDir, "*", SearchOption.AllDirectories).ToList(); subDirs.Reverse(); subDirs.ForEach(subdir => Directory.Delete(subdir, true)); Directory.Delete(targetDir, true); QuotaUsedDelete(domain, size); }
public JsonResult Insert(User user) { try { if (ModelState.IsValid) { user.Password = Crypt.EncodeSHA1(user.Password); _unitOfWork.Repository <User>().Insert(user); _unitOfWork.Save(); return(Json(new { success = true, message = "Registro Inserido com Sucesso." }, JsonRequestBehavior.AllowGet)); } else { return(this.Json(new { success = false, message = "Preencha corretamente." }, JsonRequestBehavior.AllowGet)); } } catch (DbEntityValidationException ex) { StringBuilder sb = new StringBuilder(); foreach (var failure in ex.EntityValidationErrors) { sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType()); foreach (var error in failure.ValidationErrors) { sb.AppendFormat("- {0} : {1}\n", error.PropertyName, error.ErrorMessage); sb.AppendLine(); } } return(this.Json(new { success = false, message = sb.ToString() }, JsonRequestBehavior.AllowGet)); } catch (Exception e) { return(this.Json(new { success = false, message = e.Message }, JsonRequestBehavior.AllowGet)); } }
public ObservableCollection <MPerson> Load() { ObservableCollection <MPerson> result = new ObservableCollection <MPerson>(); _XDoc = new XmlDocument(); _Stream = new FileStream(_FilePath, FileMode.Open); _XDoc.Load(_Stream); XmlNodeList list = _XDoc.GetElementsByTagName(_SubName); for (int i = 0; i < list.Count; i++) { XmlElement cl = (XmlElement)_XDoc.GetElementsByTagName(_SubName)[i]; MPerson r = new MPerson() { Id = cl.GetAttribute("Id"), VName = Crypt.DecryptString(cl.GetAttribute("VName"), cl.GetAttribute("Id")), NName = Crypt.DecryptString(cl.GetAttribute("NName"), cl.GetAttribute("Id")), Mid = Crypt.DecryptString(cl.GetAttribute("Mid"), cl.GetAttribute("Id")), TaughtNr = cl.GetAttribute("TaughtNr"), Stunden = new ObservableCollection <MStunden>() }; for (int j = 0; j < cl.ChildNodes.Count; j++) { XmlElement ca = (XmlElement)cl.ChildNodes[j]; r.Stunden.Add(new MStunden() { Id = ca.GetAttribute("Id"), Start = ca.GetAttribute("Start"), Ende = ca.GetAttribute("Ende"), Pause = ca.GetAttribute("Pause") }); } result.Add(r); } _Stream.Close(); return(result); }
public static string GetSignature(int timestamp, string requestPath, string key) { // The signature is the SHA1 result of (Timestamp + Route + key) (from http://debrid-link.fr/api_doc/#/home) // Timestamp : server unix timestamp // Route : path of the request // key : key returned by authenticating // example Timestamp + Route + key : 1418758917/account/infosi619yOI4Kt8WB02g // SHA1 result : ab90fa6a2c9f1bc2bbd7988ff266971b5c10583c string signature = timestamp.ToString() + requestPath + key; string hash = Crypt.ComputeSHA1Hash(signature).zToHex(lowercase: true); if (__trace) { pb.Trace.WriteLine(" signature : timestamp+request+key \"{0}\" = \"{1}\"", signature, hash); } //if (__trace) //{ // pb.Trace.WriteLine(" signature : \"{0}\"", signature); // pb.Trace.WriteLine(" signature sha1 : \"{0}\"", hash); //} return(hash); }
private void CopyAll(DirectoryInfo source, DirectoryInfo target, string newdomain) { // Check if the target directory exists, if not, create it. if (!Directory.Exists(target.FullName)) { Directory.CreateDirectory(target.FullName); } // Copy each file into it's new directory. foreach (var fi in source.GetFiles()) { var fp = Path.Combine(target.ToString(), fi.Name); fi.CopyTo(fp, true); var size = Crypt.GetFileSize(fp); QuotaUsedAdd(newdomain, size); } // Copy each subdirectory using recursion. foreach (var diSourceSubDir in source.GetDirectories()) { var nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name); CopyAll(diSourceSubDir, nextTargetSubDir, newdomain); } }
public IActionResult Registration([FromBody]PartnerModel user) { try { if (user == null) { return Ok(new { success = false, message = "Пустой запрос" }); } if (db.Partners.FirstOrDefault(x => x.Email == user.Email) != null) { return Ok(new { success = false, message = "Данная почта уже занята" }); } string password = user.Password; user.Password = Crypt.GeneratePassword(user.Email, user.Password); db.Partners.Add(user); db.SaveChanges(); SendMail.SendToken(db.Partners.FirstOrDefault(x=>x.Password==user.Password).Id,user.Email, password); return Ok("success"); } catch (Exception e) { return Ok(new { success = false, message = e.Message }); } }
protected void Page_Load(object sender, EventArgs e) { try { string aTickStr = Crypt.simpleDecrypt(Request["2"].ToString()); if (!isTimeOut(aTickStr)) { string aUsername = Crypt.simpleDecrypt(Request["1"].ToString()); MembershipUser aMembershipUser = Membership.GetUser(aUsername); } else { //timedout Response.Redirect("timeout.aspx"); } } catch (Exception exc) { string errorMessage = "Exception occurred. Details are: " + exc.ToString(); Logger.LogWarn(errorMessage, exc.GetType()); Trace.Warn(this.ToString(), errorMessage); } //Response.Write(aUsername); }
/// <summary> /// Verifica se a senha passada é a mesma do credenciado referente ao número de série do POS passado no parâmetro /// </summary> /// <param name="senha">senha do credenciado</param> /// <param name="numSerie">número de série do POS do credenciado desejado</param> /// <returns>retorna True caso a senha seja igual e False caso contrário</returns> //Alterado para SqlServer public static bool verificaSenhaCredPorPos(string numSerie, string senha) { SqlParamsList ps = new SqlParamsList(); ps.Add(new Fields("@numSerie", numSerie)); BD BD = new BD(); string r = Convert.ToString(BD.ExecuteScalar("select (select top 1 senha from credenciados where cred_id = p.cred_id and apagado <> 'S') senha from pos p where pos_serial_number = @numSerie", ps)); Crypt c = new Crypt(); string crypto = c.Crypt("D", r, "BIGCOMPRAS"); return crypto.Equals(senha); }
public conData_SQLITE(string xDataBaseFile, string xPassword) { DataBaseFile = xDataBaseFile; m_crypted_Password = xPassword; m_Crypt = new Crypt(encrypt_num); }
public static void Main(string[] args) { bool showHelp = false; string key = null, inputPath = null, outputPath = null, command; OptionSet opt = new OptionSet() { {"k|key=", "in decrypt is modulo key, generated in encryption", v => key = v}, {"i|in=", "input file", v => inputPath = v}, {"o|out=", "output file", v => outputPath = v}, {"h|help", "show this message and exit", v => showHelp = v != null}, }; List<string> commands; try { commands = opt.Parse(args); } catch (OptionException e) { PrintError(e.Message); return; } if (showHelp) { Usage(opt); return; } if (0 == commands.Count) { PrintError("There is no command."); return; } command = commands[0]; if ("encrypt" != command && "decrypt" != command) { PrintError("Invalid command."); return; } if ("decrypt" == command && null == key) { PrintError("There is no key to decrypt message."); return; } if (null == inputPath) { PrintError("The input file is not specified"); return; } if (null == outputPath) { PrintError("The output file is not specified"); return; } FileStream inputFile, outputFile; try { inputFile = File.Open(inputPath, FileMode.Open, FileAccess.Read, FileShare.None); outputFile = File.Open(outputPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); } catch (Exception e) { PrintError(e.Message); return; } Crypt crypt = new Crypt(); crypt.inputFile = inputFile; crypt.outputFile = outputFile; string outputText = ""; switch (command) { case "encrypt": outputText = crypt.Encrypt(); break; case "decrypt": crypt.key = key; outputText = crypt.Decrypt(); break; } Console.WriteLine(outputText); inputFile.Close(); outputFile.Close(); }