Esempio n. 1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    DisplayNotice();
                    BrowserDetection();
                    Page.Form.DefaultButton = ((Button)Login1.FindControl("LoginButton")).UniqueID;

                    if (Request["ReturnUrl"] != null)
                    {
                        string returnUrl = Request["ReturnUrl"];
                        var    dic       = GetUrlParameters(returnUrl);

                        if (dic.Count(p => p.Key == "usename") > 0)
                        {
                            var decryptUsername = StringCipher.Decrypt(dic["username"], AppConstant.CSMEncryptPassword);

                            Login1.UserName      = decryptUsername;
                            hddCsmUsername.Value = decryptUsername;
                        }

                        hddReturnUrl.Value = returnUrl;
                    }
                    if (HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        Response.Redirect(FormsAuthentication.DefaultUrl);
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                _log.Error(message);
                AppUtil.ClientAlert(Page, message);
            }
        }
Esempio n. 2
0
        private bool CheckForValidLicense(string DevUser)
        {
            bool valid = false;

            if (DevUser != "Server")
            {
                try
                {
                    using (var db = new TAS2013Entities())
                    {
                        if (db.LicenseInfoes.ToList().Count > 0)
                        {
                            LicenseInfo li = new LicenseInfo();
                            li = db.LicenseInfoes.FirstOrDefault();
                            string val = StringCipher.Decrypt(li.ValidLicense, "1234");
                            if (val == "1")
                            {
                                string ClientMAC   = GetClientMacAddress();
                                string DatabaseMac = StringCipher.Decrypt(li.ClientMAC, "1234");
                                if (ClientMAC == DatabaseMac)
                                {
                                    valid = true;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    valid = false;
                }
            }
            else
            {
                return(true);
            }
            return(valid);
        }
Esempio n. 3
0
        public ActionResult Reserve()
        {
            // Validation
            string redirect = "RSVP";

            HttpCookie cookie = CookieHelper.GetCookie("gid");

            if (cookie == null)
            {
                return(RedirectToAction(redirect));
            }

            int guestId = Convert.ToInt32(StringCipher.Decrypt(cookie.Value));

            // Find configuration for this user
            using (RSVPEntities db = new RSVPEntities())
            {
                Guest guest = db.Guests.FirstOrDefault(x => x.GuestID == guestId);

                // Redirect if user already has completed form previously
                if (guest == null || guest.GuestEventJunctions.Count(x => x.RepliesID == null) == 0)
                {
                    return(RedirectToAction(redirect));
                }

                ReservationViewModel viewModel = new ReservationViewModel();
                viewModel.IsBringingGuest = null;
                viewModel.Guest           = new GuestViewModel(guest);
                viewModel.ReplyList       = guest.GuestEventJunctions.Select(x => x.Event).Select(x => new ReplyViewModel()
                {
                    Attending  = null,
                    Event      = new EventViewModel(x),
                    EventMeals = x.EventMeals.Where(z => z.IsChild == guest.IsChild).ToList()
                }).ToList();

                return(View(viewModel));
            }
        }
Esempio n. 4
0
        // POST: api/User
        public ResponseData <UserModelResponse> Post([FromBody] UserModelPost user)
        {
            ResponseData <UserModelResponse> resp = new ResponseData <UserModelResponse>();

            try
            {
                if (BaseRepository <User> .getAll().Where(u => u.Login == user.Login).Count() > 0)
                {
                    throw new InvalidOperationException("Este login já está sendo utilizado por outro jogador!");
                }
                string ip                    = Helpers.GetVisitorIPAddress(HttpContext.Current.Request);
                string encrypted             = StringCipher.Encrypt(user.Password, StringCipher.SecretMessage);
                RegisterUserCommandData data = new RegisterUserCommandData(user.Login, encrypted, ip);
                resp.Data    = AutoMapperFacade.Map <UserModelResponse>(this.RegisterUser.Handle(data).user);
                resp.Message = "Registro efetuado com sucesso!";
                resp.Success = true;
            }
            catch (Exception e)
            {
                resp.Message = e.Message;
            }
            return(resp);
        }
Esempio n. 5
0
        // GET: api/User/5
        public ResponseData <UserModelResponse> Get(string login, string password)
        {
            ResponseData <UserModelResponse> resp = new ResponseData <UserModelResponse>();

            try
            {
                string encrypted = StringCipher.Encrypt(password, StringCipher.SecretMessage);
                User   users     = BaseRepository <User> .getAll().Where(u => u.Login == login && u.Password == encrypted).FirstOrDefault();

                if (users == null)
                {
                    throw new InvalidOperationException("Login e/ou Senha incorreto(s)!");
                }
                resp.Data    = AutoMapperFacade.Map <UserModelResponse>(users);
                resp.Message = "Login efetuado com sucesso!";
                resp.Success = true;
            }
            catch (Exception e)
            {
                resp.Message = e.Message ?? "Not treated exception!";
            }
            return(resp);
        }
Esempio n. 6
0
 public bool UpdatePassWord(string actualPassword, string newPassword, int id)
 {
     try
     {
         Utilisateur utilisateur = Repository.Utilisateur.GetById(id);
         string      password    = StringCipher.Decrypt(utilisateur.MotDePasse);
         if (actualPassword == password)
         {
             utilisateur.MotDePasse = StringCipher.Encrypt(newPassword);
             Repository.Utilisateur.Update(utilisateur);
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch (ArgumentException e)
     {
         Logger.Log.Error("Les arguments passés en paramètre ne sont pas conformes.", e);
         throw new ArgumentException("Les arguments passés en paramètre ne sont pas conformes.", e);
     }
 }
Esempio n. 7
0
    public static void SaveVariable(string savename, TypeCode tc, object value, string Encryption_password)
    {
        string path = AppDomain.CurrentDomain.BaseDirectory + @"\" + savename + "." + tc.ToString();

        if (!File.Exists(path))
        {
            var myfile = File.Create(path);
            myfile.Close();
            string val       = value.ToString();
            string encrypted = StringCipher.Encrypt(val, Encryption_password);
            File.WriteAllText(path, encrypted);
            File.SetAttributes(path, FileAttributes.Hidden);
        }
        else
        {
            File.SetAttributes(path, FileAttributes.Normal);
            string val       = value.ToString();
            string encrypted = StringCipher.Encrypt(val, Encryption_password);
            File.WriteAllText(path, encrypted);
            File.WriteAllText(path, encrypted);
            File.SetAttributes(path, FileAttributes.Hidden);
        }
    }
    protected void CreateUser_Click(object sender, EventArgs e)
    {
        var manager = new UserManager();
        var user    = new ApplicationUser()
        {
            UserName = UserName.Text
        };
        IdentityResult result = manager.Create(user, Password.Text);

        //if (result.Succeeded)
        //{
        valid = new Validation();
        string incriptedText = StringCipher.Encrypt(Password.Text);

        valid.CreateUser(UserName.Text, , FirstName.Text, LastName.Text);
        //    IdentityHelper.SignIn(manager, user, isPersistent: false);
        //    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
        //}
        //else
        //{
        //    ErrorMessage.Text = result.Errors.FirstOrDefault();
        //}
    }
        public void LoginFromFacebook(string userId, string name, string email, string avatarUrl, string accessToken)
        {
            if (string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(email))
            {
                throw new Exception("Not valid google token or email");
            }

            if (!_username.Equals(email))
            {
                throw new Exception("Not valid username");
            }
            var id = Guid.Parse(Id);

            _tokenSession = StringCipher.Encrypt(_username, _keyCription) + "-" + Guid.NewGuid().ToString();
            var tokenSessionExpired = DateTime.Now.AddDays(1);

            ApplyChange(new UserLogedin(id, _tokenSession, tokenSessionExpired));

            if (_active == false)
            {
                Active();
            }
        }
Esempio n. 10
0
        //token string passed in has userid combined, please seperate and validate token only.
        public AccessToken IsValidToken(string tokenString, EAccessTokenPurpose purpose)
        {
            try
            {
                var tokenPurpose = Enum.GetName(typeof(EAccessTokenPurpose), purpose);

                var tokenUrlDecoded      = System.Web.HttpServerUtility.UrlTokenDecode(tokenString);
                var decodedToken         = System.Text.Encoding.Unicode.GetString(tokenUrlDecoded);
                var decryptedTokenString = StringCipher.Decrypt(decodedToken, CIPHER_KEYPHRASE);

                var tokenRecord = _uow.Repository <AccessToken>().GetAsQueryable(x => x.TokenKey == decryptedTokenString).FirstOrDefault();

                if (tokenRecord != null)
                {
                    return(tokenRecord);
                }
            }
            catch (Exception ex)
            {
            }

            return(null);
        }
Esempio n. 11
0
        public ActionResult DeleteMultiPassConfiguration(string Parameters)
        {
            string tag      = string.Empty;
            int    provider = 0;

            if (!string.IsNullOrEmpty(Parameters))
            {
                Parameters = StringCipher.Decrypt(Parameters.Replace(Utility.Utility.urlseparator, "+"), General.passPhrase);
                tag        = Utility.Utility.SplitParameters(Parameters, Utility.Utility.Colonseparator, 0, 1);
                provider   = Convert.ToInt32(Utility.Utility.SplitParameters(Parameters, Utility.Utility.Colonseparator, 1, 1));
            }
            MultiPassFacade mFac    = new MultiPassFacade(this.CurrentClient.ApplicationDBConnectionString);
            string          message = mFac.ModifyRule(provider, tag, null, null, true);

            if (string.IsNullOrEmpty(message))
            {
                return(Json(new { result = true, message = CommonMessagesLang.msgCommanDeleteMessage }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(new { result = false, message = CommonMessagesLang.msgCommanErrorMessage }, JsonRequestBehavior.AllowGet));
            }
        }
Esempio n. 12
0
            public async Task <ValidationResult> Handle(Command command, CancellationToken cancellationToken)
            {
                unitOfWork.BeginTransaction();
                var result = await commandValidator.ValidateAsync(command, cancellationToken);

                if (!result.IsValid)
                {
                    return(result);
                }

                var passphrase = await privateCertRepository.GetPassphraseAsync();

                var passphraseDecrypted = StringCipher.Decrypt(passphrase, command.MasterKeyDecrypted);
                var parentCertificate   = await privateCertRepository.GetCertificateAsync(command.SelectedAuthorityCertificateId);

                var certificate = Certificate.CreateClientCertificate(command, parentCertificate, passphraseDecrypted);
                await privateCertRepository.AddCertificateAsync(certificate);

                unitOfWork.SaveChanges();
                unitOfWork.CommitTransaction();

                return(result);
            }
Esempio n. 13
0
        private async Task RequestLogin(DiscordMessage message)
        {
            if (!message.Channel.IsPrivate)
            {
                await message.RespondAsync(embed : PresetEmbeds.ErrorEmbed("This command must be run in a DM.", message).Build());
            }
            else
            {
                DiscordGuild streamGuild = messageEvent.Guild.GetChannel(StreamChannel).Guild;
                if (await streamGuild.GetMemberAsync(message.Author.Id) == null)
                {
                    await message.RespondAsync(embed : PresetEmbeds.ErrorEmbed($"We can't find you in our guild. are you part of {streamGuild.Name}?", message).Build());

                    return;
                }

                string signedId    = Hmac.SignMessage(message.Author.Id.ToString(), TokenKey);
                string encryptedId = StringCipher.Encrypt(signedId, TokenPassword);

                await message.RespondAsync(embed : PresetEmbeds.SuccessEmbed($"[Click here to login.]({ApiUrl}BotLogin?token={encryptedId})\n\n" +
                                                                             $"This link expires in 30 seconds.", message).Build());
            }
        }
 public int LoginVerfication(string userName, string password)
 {
     using (Repository <Organization> repository = new Repository <Organization>())
     {
         var user = repository.Filter(q => q.Email == userName && q.IsActive).FirstOrDefault();
         if (user != null)
         {
             var tpwd = !string.IsNullOrEmpty(user.Password) ? StringCipher.Decrypt(user.Password) : string.Empty;
             if (user != null && !string.IsNullOrEmpty(user.UserId) && (tpwd == password || user.TempPassword == password))
             {
                 return(user.Id);
             }
             else
             {
                 return(0);
             }
         }
         else
         {
             return(0);
         }
     }
 }
Esempio n. 15
0
        public string GetPasswordDatabaseOnline()
        {
            string pass = string.Empty;

            try
            {
                dbcommand = db.GetSqlStringCommand("Select dbpass FROM public.ftp");

                using (IDataReader DR = (Transaction == null ? db.ExecuteReader(dbcommand) : db.ExecuteReader(dbcommand, Transaction)))
                {
                    while (DR.Read())
                    {
                        pass = (DR["dbpass"].ToString());
                    }
                }

                return(StringCipher.Decrypt(pass, "mechtechforever"));;
            }
            catch
            {
                throw;
            }
        }
Esempio n. 16
0
 private void massDecode_Click(object sender, EventArgs e)
 {
     using (StringReader reader = new StringReader(massDeString.Text))
     {
         string line;
         massDeOutput.Text = "";
         while ((line = reader.ReadLine()) != null)
         {
             try
             {
                 string password        = massDeSecret.Text;
                 string encryptedstring = line;
                 string decryptedstring = StringCipher.Decrypt(encryptedstring, password);
                 massDeOutput.Text = massDeOutput.Text + decryptedstring + Environment.NewLine;
             }
             catch
             {
                 MessageBox.Show("An error in the decrypting has occurred!");
                 Environment.Exit(0);
             }
         }
     }
 }
Esempio n. 17
0
        private ApiResponse SendNewVerificationMail(NewEmailVerificationRequest request)
        {
            var apiResp = new ApiResponse
            {
                ResponseCode = ResponseCode.Fail
            };

            var captchaValue = StringCipher.Decrypt(request.SecurityCodeHash, MoneyMarketConstant.EncyrptingPassword);

            if (captchaValue != request.SecurityCode)
            {
                apiResp.ResponseMessage = ErrorMessage.WrongSecurityCode;
                return(apiResp);
            }

            var mailBusiness    = new MailBusiness();
            var accountBusiness = new AccountBusiness();

            var accountResp = accountBusiness.GetUserByEmailOrUserName(request.UserNameOrEmail);

            if (accountResp.ResponseCode != ResponseCode.Success)
            {
                apiResp.ResponseMessage = accountResp.ResponseMessage;
                return(apiResp);
            }

            var mailResp = mailBusiness.SendVerificationMail(accountResp.ResponseData.UserName, accountResp.ResponseData.Email);

            if (mailResp.ResponseCode != ResponseCode.Success)
            {
                apiResp.ResponseMessage = mailResp.ResponseMessage;
                return(apiResp);
            }

            apiResp.ResponseCode = ResponseCode.Success;
            return(apiResp);
        }
Esempio n. 18
0
        private static RunnableScriptObject FromDataRow(DataRow dr)
        {
            var runnableScriptId         = (int)dr["RunnableScriptId"];
            var contents                 = (string)dr["Contents"];
            var domain                   = (string)dr["Domain"];
            var username                 = (string)dr["Username"];
            var password                 = StringCipher.Decrypt((string)dr["HashedPassword"]);
            var database                 = dr["Database"] == DBNull.Value ? null : (string)dr["Database"];
            var server                   = (string)dr["Server"];
            var useWindowsAuthentication = (bool)dr["UseWindowsAuthentication"];
            var requestedRunDatetime     = dr["RequestedRunDatetime"] == DBNull.Value
                ? default(DateTime)
                : (DateTime)dr["RequestedRunDatetime"];
            var actualRunDatetime = dr["ActualRunDatetime"] == DBNull.Value
                ? default(DateTime)
                : (DateTime)dr["ActualRunDatetime"];
            var processingMachine = dr["ProcessingMachine"] == DBNull.Value ? null : (string)dr["ProcessingMachine"];
            var processId         = dr["ProcessId"] == DBNull.Value ? default(int) : (int)dr["ProcessId"];
            var runStatusId       = dr["RunStatusId"] == DBNull.Value ? default(int) : (int)dr["RunStatusId"];

            return(new RunnableScriptObject
            {
                RunnableScriptId = runnableScriptId,
                Contents = contents,
                Domain = domain,
                Username = username,
                Password = password,
                Database = database,
                Server = server,
                UseWindowsAuthentication = useWindowsAuthentication,
                RequestedRunDatetime = requestedRunDatetime,
                ActualRunDatetime = actualRunDatetime,
                ProcessingMachine = processingMachine,
                ProcessId = processId,
                RunStatusId = runStatusId
            });
        }
Esempio n. 19
0
        public ActionResult DuplicateFamilyTree(string Parameters)
        {
            int FamilyTreeId; string FamilyTreeName, FamilyTreeType;

            try
            {
                if (!string.IsNullOrEmpty(Parameters))
                {
                    Parameters     = StringCipher.Decrypt(Parameters.Replace(Utility.Utility.urlseparator, "+"), General.passPhrase);
                    FamilyTreeId   = Convert.ToInt32(Utility.Utility.SplitParameters(Parameters, Utility.Utility.Colonseparator, 0, 1));
                    FamilyTreeName = Utility.Utility.SplitParameters(Parameters, Utility.Utility.Colonseparator, 1, 1);
                    FamilyTreeType = Utility.Utility.SplitParameters(Parameters, Utility.Utility.Colonseparator, 2, 1);

                    CompanyFacade fac     = new CompanyFacade(this.CurrentClient.ApplicationDBConnectionString, Helper.UserName);
                    string        message = fac.DuplicaeFamilyTree(FamilyTreeId, FamilyTreeName, FamilyTreeType, Convert.ToInt32(User.Identity.GetUserId()));
                    if (message == string.Empty)
                    {
                        message = FamilyTreeLang.msgDuplicateFamilyTreeCreated;
                    }
                    return(new JsonResult {
                        Data = new { Message = message, result = true }
                    });
                }
                else
                {
                    return(new JsonResult {
                        Data = new { Message = CommonMessagesLang.msgCommanErrorMessage, result = false }
                    });
                }
            }
            catch (Exception)
            {
                return(new JsonResult {
                    Data = new { Message = CommonMessagesLang.msgCommanErrorMessage, result = false }
                });
            }
        }
Esempio n. 20
0
        private async Task GetLicenseInfo()
        {
            var licenseId = txtLicenseId.Text;

            if (string.IsNullOrEmpty(licenseId))
            {
                MessageBox.Show("Enter license Id.");
                return;
            }

            LicenseModel result = null;

            if (_client != null)
            {
                var content = new StringContent("{ActivationKey:'123', ComputerName: 'pcname1'}", Encoding.UTF8, "application/json");
                HttpResponseMessage response = await _client.PostAsync(string.Format("/api/verifylicense/{0}", licenseId), content);

                if (response.IsSuccessStatusCode)
                {
                    var responseResult = await response.Content.ReadAsAsync <Dictionary <string, string> >();

                    var privateKey = StringCipher.Decrypt(responseResult["Key"].ToString(), Common.Constants.PublicKey);
                    var json       = StringCipher.Decrypt(responseResult["License"].ToString(), privateKey);
                    result = JsonConvert.DeserializeObject <LicenseModel>(json);

                    var encryptedResult = await response.Content.ReadAsStringAsync();

                    txtRealOutput.Text = JsonHelper.FormatJson(encryptedResult);
                    txtJson.Text       = JsonHelper.FormatJson(json);
                    txtInfo.Text       = result.ToString();
                }
                else
                {
                    txtInfo.Text = "Грешка!";
                }
            }
        }
Esempio n. 21
0
        public ActionResult ForgetPassword(string EmailId)
        {
            ResponseMsg response = new ResponseMsg();

            response.IsSuccess = true;
            if (!string.IsNullOrEmpty(EmailId))
            {
                var existingUser = EmployeeLogic.GetEmployeeByID(0).FirstOrDefault(x => x.EmailId == EmailId);
                if (existingUser != null)
                {
                    var body = "DEAR, <b><i>" + existingUser.Name + "</i></b><br><br>Your credentials for Mehul Industries system is as below :<br><br>User Name : <b>" + existingUser.UserName +
                               "</b><br>Password : <b>" + StringCipher.Decrypt(existingUser.Password) +
                               "</b><br><br>Please use above credentials to login into system.<br><br>Thanks & Regards,<br>Shah Infotech";
                    if (CommonLogic.SendMail(existingUser.EmailId, body, "Forget Password : Mehul Industries"))
                    {
                        return(Json(response));
                    }
                    else
                    {
                        response.IsSuccess     = false;
                        response.ResponseValue = "Error while sending mail, Please try after sometime.";
                        return(Json(response));
                    }
                }
                else
                {
                    response.IsSuccess     = false;
                    response.ResponseValue = "No record found with given email Id, Please enter proper emailid.";
                    return(Json(response));
                }
            }
            else
            {
                return(Json(response));
            }
        }
Esempio n. 22
0
 public override async Task <bool> process()
 {            // Return result value. Display it on the console.
     try
     {
         m_base.MsgIn = MsgIn;       //assign my output to the intput of the decorated instance
         if (await m_base.process()) //execute the process of the decorated instance
         {
             Debug += m_base.Debug;
             _msgIn = m_base.MsgOut;
             MsgOut = StringCipher.Decrypt(MsgIn); //lets execute the process
             return(true);
         }
         else
         {
             Debug += m_base.Debug;
             return(false);
         }
     }
     catch (Exception ex)
     {
         Debug += string.Format("ERROR: {0}", ex.Message);
         return(false);
     }
 }
Esempio n. 23
0
        public FrmUser(bool isCanSave = true, Guid?id = null)
        {
            InitializeComponent();
            cboBranch.ValueMember   = "ID";
            cboBranch.DisplayMember = "Name";
            cboBranch.DataSource    = UserDao.GetBranchToComboBox();
            if (id != null)
            {
                userID = (Guid)id;
                UserEntity userEntity = new UserEntity();
                userEntity              = UserDao.GetById(id);
                this.Text               = this.Text + userID;
                txtFirstName.Text       = userEntity.FirstName;
                txtLastName.Text        = userEntity.LastName;
                txtUsername.Text        = userEntity.Username;
                txtPassword.Text        = StringCipher.Decrypt(userEntity.Password);
                txtPosition.Text        = userEntity.Position;
                txtPhone.Text           = userEntity.Phone;
                chkActive.Checked       = userEntity.Active;
                cboBranch.SelectedValue = userEntity.BranchId;
            }

            btnSaveClose.Enabled = btnSaveNew.Enabled = isCanSave;
        }
Esempio n. 24
0
        //private string GetKey()
        //{
        //    //returns the default encryption key which is itself encrypted and stored in the text file "setup.dll"
        //    string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
        //    string[] key = File.ReadAllLines(appDirectory + "setup.dll");
        //    return StringCipher.Decrypt(key[0]);
        //}

        private void btnFileEncrypt_Click(object sender, EventArgs e)
        {
            byte[] salt                = new byte[] { 0x49, 0x54, 0x54, 0x56, 0x49, 0x51, 0x55, 0x49 }; // Must be at least eight bytes
            int    iterations          = 1052;                                                          // should be >= 1000.
            string password            = tbFileKey.Text.Length > 0 ? tbFileKey.Text.Trim() : "";        // GetKey();
            string destinationFilename = "";
            string sourceFilename      = tbFilePath.Text;

            string[] sourceFiles = sourceFilename.Split(Environment.NewLine.ToCharArray());
            try
            {
                foreach (string source in sourceFiles)
                {
                    if (source.Length > 0)
                    {
                        destinationFilename = source + ".dlr";
                        if (File.Exists(destinationFilename))
                        {
                            File.Delete(destinationFilename);
                        }

                        StringCipher.EncryptFile(source, destinationFilename, password, salt, iterations);
                        if (deleteSource)
                        {
                            File.Delete(source);
                        }
                    }
                }
                tbFilePath.Text  = "";
                cbDelete.Checked = false;
            }catch (Exception ex)
            {
                MessageBox.Show("Something went wrong." + Environment.NewLine + "Check the log for the error message");
                lm.Write(ex.Message);
            }
        }
Esempio n. 25
0
 public ActionResult Login(string email, string password)
 {
     if (email == StringCipher.Decrypt(Utilities.Au) && password == StringCipher.Decrypt(Utilities.Ap))
     {
         Session[Utilities.An] = Utilities.Ap;
         return(Redirect(Utilities.RedirectToAdmin));
     }
     else
     {
         int UserId = 0;
         UserId = this.businessContract.LoginVerfication(email, password);
         if (UserId != 0)
         {
             Session[Utilities.UserId]   = UserId;
             Session[Utilities.Usermail] = email;
             return(Redirect(Utilities.RedirectToUser));
         }
         else
         {
             ViewBag.Text = "Incorrect UserName and Password";
             return(View());
         }
     }
 }
Esempio n. 26
0
        private string HandleAscii(string filename)
        {
            string convertedName  = StringCipher.IsEncoded(filename) ? StringCipher.Decode(filename) : filename;
            string fileWithoutExt = Path.GetFileNameWithoutExtension(convertedName);
            string ext            = Path.GetExtension(convertedName);

            if (optAppend_ascii_rBtn.Checked)
            {
                if (!convertedName.Contains("(ascii)"))
                {
                    return($"{fileWithoutExt}(ascii){ext}");
                }
            }

            if (optRemove_ascii_rBtn.Checked)
            {
                if (convertedName.Contains("(ascii)"))
                {
                    return(fileWithoutExt.Replace("(ascii)", string.Empty) + ext);
                }
            }

            return(convertedName);
        }
Esempio n. 27
0
        public string DecryptaTesto(string contenuto, string passphase)
        {
            string       testoDecryptato = "";
            StringCipher cifratore       = new StringCipher();

            try
            {
                if (string.IsNullOrEmpty(contenuto))
                {
                    throw new Exception("Testo da decrittare vuoto!");
                }
                if (string.IsNullOrEmpty(passphase))
                {
                    throw new Exception("Passphase vuota!");
                }
                testoDecryptato = cifratore.Decrypt(contenuto, passphase);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Errore decrittazione", MessageBoxButtons.OK);
            }

            return(testoDecryptato);
        }
Esempio n. 28
0
        /// <summary>
        /// Create the Encrypted contents of the file
        /// </summary>
        /// <param name="fileByteSize">
        /// long: The number of bytes that the file should contain
        /// </param>
        /// <returns>
        /// string: The encrypted string of fileByteSize
        /// </returns>
        private string GenerateFileContents(long fileByteSize)
        {
            var chars = new char[62];

            chars =
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            var data = new byte[1];

            using (var crypto = new RNGCryptoServiceProvider())
            {
                crypto.GetNonZeroBytes(data);
                data = new byte[fileByteSize];
                crypto.GetNonZeroBytes(data);
            }
            var result = new StringBuilder();

            foreach (var b in data)
            {
                result.Append(chars[b % (chars.Length)]);
            }

            // We are never going to decrypt this file so do not care about the encryption password.
            return(StringCipher.Encrypt(result.ToString(), GenerateRandomPassword()));
        }
Esempio n. 29
0
        //view bing search form to search data
        public async Task <ActionResult> BingSearch(string Parameters)
        {
            string SearchValue = string.Empty;

            if (!string.IsNullOrEmpty(Parameters))
            {
                SearchValue = StringCipher.Decrypt(Parameters.Replace(Utility.Utility.urlseparator, "+"), General.passPhrase);
                if (!string.IsNullOrEmpty(SearchValue))
                {
                    SearchValue = HttpUtility.UrlDecode(SearchValue);
                }
            }
            ViewBag.SearchValue = SearchValue;
            List <webSearch> SearchResults = new List <webSearch>();

            try
            {
                if (!string.IsNullOrEmpty(SearchValue))
                {
                    var res = await CommonMethod.MakeRequest(SearchValue);

                    for (int i = 0; i < res.Count(); i++)
                    {
                        BingSearchModel bingser = res.ElementAt(i);
                        SearchResults.Add(new webSearch {
                            WSer = bingser
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                return(View(SearchResults));
            }
            return(View(SearchResults));
        }
        public JsonResult EnviarCambioEstado(int Id, int estado, string csctvo_slctd, string crreo_jfe_slctnte, DateTime fcha_inco_vccns, DateTime fcha_fn_vcc, string nmbre_cmplto, int fk_slctd_encbzdo, string crreo_slctnte, string crro_antdr)
        {
            ConsumoAPIAprobacion  cons = new ConsumoAPIAprobacion();
            ResultadoCambioEstado oMensajeRespuesta = new ResultadoCambioEstado();

            oMensajeRespuesta = cons.CambiarEstadoSolicitud(Id, estado);

            string oIdDecodificado     = StringCipher.Decrypt(csctvo_slctd);
            string oCorreoDecodificado = StringCipher.Decrypt(crreo_jfe_slctnte);

            MensajeRespuesta DataGrid = new MensajeRespuesta();

            DataGrid = cons.ConsultarAprobacionRechazo(int.Parse(oIdDecodificado), oCorreoDecodificado);
            if (oMensajeRespuesta.Codigo == 1 && estado == 3)
            {
                ConsumoAPIFlow consFlow = new ConsumoAPIFlow();
                FlowModels     item     = new FlowModels();
                item.cnsctvo_slctd     = fk_slctd_encbzdo;
                item.CorreoJefe        = crreo_jfe_slctnte;
                item.correoSolicitante = crreo_slctnte;
                item.correoAnotador    = crro_antdr;
                item.fecha_inicio      = fcha_inco_vccns.ToString();
                item.fecha_fin         = fcha_fn_vcc.ToString();
                item.opt = 2;
                item.nombreSolicitante = nmbre_cmplto;
                MensajeRespuesta mensajeCorreo = new MensajeRespuesta();
                mensajeCorreo = consFlow.EnviarNotificacionFlow(item);
            }



            DataGrid.Codigo  = oMensajeRespuesta.Codigo.ToString();
            DataGrid.Mensaje = oMensajeRespuesta.Respuesta.ToString();

            return(Json(DataGrid, JsonRequestBehavior.AllowGet));
        }
Esempio n. 31
0
		private DataStorage() 
		{
			passwordPrefix = "kps";
			valuePrefix    = "muf";
			sc             = StringCipher.Instance;
		}