public override void Update(double totalMS, double frameMS) { if (_lastLoginStep != CurrentLoginStep) { Engine.UI.GameCursor.IsLoading = false; // this trick avoid the flickering var g = _currentGump; Engine.UI.Add(_currentGump = GetGumpForStep()); g.Dispose(); _lastLoginStep = CurrentLoginStep; } if (Reconnect && (CurrentLoginStep == LoginStep.PopUpMessage || CurrentLoginStep == LoginStep.Main)) { long rt = (long)totalMS + Engine.GlobalSettings.ReconnectTime * 1000; if (_reconnectTime == null) { _reconnectTime = rt; } if (_reconnectTime < totalMS) { if (!string.IsNullOrEmpty(Account)) { Connect(Account, Crypter.Decrypt(Engine.GlobalSettings.Password)); } else if (!string.IsNullOrEmpty(Engine.GlobalSettings.Username)) { Connect(Engine.GlobalSettings.Username, Crypter.Decrypt(Engine.GlobalSettings.Password)); } _reconnectTime = rt; _reconnectTryCounter++; } } base.Update(totalMS, frameMS); }
public IActionResult Edit(UserModel userModel) { try { if (ModelState.IsValid) { var userDb = _db.DbUser.Select(userModel.userId); if (userDb.password != userModel.password) { userModel.password = Crypter.GetMD5(userModel.password); } var user = _mapper.Map <User>(userModel); _db.DbUser.Update(user); return(Json(new { action = Url.Action("Index", new { message = "Usuário atualizado com sucesso!", status = OperationResult.Success }), status = OperationResult.Success })); } else { return(Json(new { action = Url.Action("Index", new { message = "Por favor preencha todos os campos obrigatórios!", status = OperationResult.Error }), status = OperationResult.Error })); } } catch (Exception e) { Logger.SaveLog(e, _configuration); return(Json(new { action = Url.Action("Index", new { message = "Erro ao atualizar usuário!", status = OperationResult.Error }), status = OperationResult.Error })); } }
public static bool Login(string username, string password) { username = username.ToUpper(); String[,] storedUserData = Server_Variables.Userdata.UserData; // I'm very lazy :3 - Soy muy perezoso :3 for (int i = 0; i < storedUserData.Length; i++) { if (storedUserData[i, 0] == username) { if (Crypter.CheckPassword(password, storedUserData[i, 1])) { return(true); } else { return(false); } } } return(false); }
public static object LoadCrypted(string _key, string _path) { BinaryFormatter bf = new BinaryFormatter(); object i; using (FileStream s = File.OpenRead(_path)) { byte[] array = new byte[s.Length]; s.Read(array, 0, array.Length); string text = Encoding.Default.GetString(array); text = Crypter.Decode(_key, text); byte[] outArray = Encoding.Default.GetBytes(text); Stream stream = new MemoryStream(outArray); i = bf.Deserialize(stream); } return(i); }
private void AuthUser(MResponse ClientResponse, MNetworkClient NetworkClient) { try { using (var db = new DatabaseContext()) { var UserData = Package.Unpacking <string[]>(ClientResponse.DataBytes); var user = db.Users.Where(u => u.Email == UserData[0]).FirstOrDefault(); if (user == null) { user = db.Users.Where(u => u.Login == UserData[0]).FirstOrDefault(); } if (user != null) { if (Crypter.CheckPassword(UserData[1], user.Password)) { if (Users.ActiveUsers.Exists(x => x.Login == user.Login)) { Sender.Send(NetworkClient, "User.Auth.Error", default, 2);
private void Encrypt(object sender, RoutedEventArgs e) { if (string.IsNullOrWhiteSpace(KeyInput.Text)) { Encode(TextInput.Text); StatusLabel.Content = "Encrypted without key"; } else if (Guid.TryParse(KeyInput.Text.Trim(), out var guid)) { var text = Crypter.Encrypt(TextInput.Text, guid); Encode(text); StatusLabel.Content = "Encrypted with given key"; } else { StatusLabel.Content = "Invalid key"; } }
private void Decrypt(object sender, RoutedEventArgs routedEventArgs) { if (string.IsNullOrWhiteSpace(KeyInput.Text)) { TextInput.Text = LSB.Decode(bitmap); StatusLabel.Content = "Decrypted without key"; } else if (Guid.TryParse(KeyInput.Text.Trim(), out var guid)) { var text = LSB.Decode(bitmap); TextInput.Text = Crypter.Decrypt(text, guid); StatusLabel.Content = "Decrypted with given key"; } else { StatusLabel.Content = "Invalid key"; } }
//Fonction qui affiche les informations du traitement en cours private static void DisplayInfo(string action, string sourcePath, string destPath) { try { string str = action + " start at " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); int bufWidth = Console.BufferWidth - 1; string sep = Crypter.StrDup(bufWidth, "="); Log.Display("= " + str.PadRight(bufWidth - 4) + " =", Log.ColorInfo); Log.Display("= " + ("Source: " + sourcePath).PadRight(bufWidth - 4) + " =", Log.ColorInfo); if (string.IsNullOrEmpty(destPath) == false) { Log.Display("= " + ("Dest : " + destPath).PadRight(bufWidth - 4) + " =", Log.ColorInfo); } Log.Display(sep, Log.ColorInfo); } catch (Exception ex) { Console.WriteLine(ex.Message, ex.StackTrace); //throw; } }
public IActionResult CadastrarCandidato(CadastrarCandidatoViewModel NovoCandidato) { try { VerificacaoViewModel vm = new VerificacaoViewModel() { Email = NovoCandidato.Email, Rg = NovoCandidato.Email, Cpf = NovoCandidato.Cpf, Telefone = NovoCandidato.Telefone, LinkLinkedinCandidato = NovoCandidato.LinkLinkedinCandidato }; if (NovoCandidato.CaminhoImagem == null || NovoCandidato.CaminhoImagem.Length <= 2) { NovoCandidato.CaminhoImagem = "user.png"; } var Response = usuarioRepository.VerificarSeCredencialJaFoiCadastrada(vm); if (Response == null) { NovoCandidato.Senha = Crypter.Criptografador(NovoCandidato.Senha); if (usuarioRepository.CadastrarCandidato(NovoCandidato)) { return(Ok("Novo candidato inserido com sucesso!")); } else { return(BadRequest("Um erro ocorreu ao receber a sua requisição.")); } } else { return(BadRequest(Response)); } } catch (Exception) { return(BadRequest("Uma exceção ocorreu. Tente novamente.")); } }
protected IKeySet ProduceKeySet(string location, string crypterLocation, bool password, out IDisposable d1, out IDisposable d2, out IDisposable d3) { if (String.IsNullOrWhiteSpace(location)) { d1 = null; d2 = null; d3 = null; return(null); } Crypter crypter = null; IKeySet ks = new KeySet(location); Func <string> prompt = CachedPrompt.Password(Util.PromptForPassword).Prompt; IDisposable dks = null; if (!String.IsNullOrWhiteSpace(crypterLocation)) { if (password) { var cks = new PbeKeySet(crypterLocation, prompt); crypter = new Crypter(cks); dks = cks; } else { crypter = new Crypter(crypterLocation); } ks = new EncryptedKeySet(ks, crypter); } else if (_password) { ks = new PbeKeySet(ks, prompt); } d1 = crypter; d2 = dks; d3 = ks as IDisposable; return(ks); }
public MainViewModel() { OverlayService.GetInstance().Show = delegate(string str, string str1) { OverlayService.GetInstance().Text = str; OverlayService.GetInstance().Description = str1; }; Items = File.Exists("Data/Items.json") ? JsonConvert.DeserializeObject <ObservableCollection <Item> >( Crypter.Decrypt(File.ReadAllText("Data/Items.json"), true)) : new ObservableCollection <Item>(); Items.CollectionChanged += (s, e) => { if (!File.Exists("Data")) { Directory.CreateDirectory("Data"); } File.WriteAllText("Data/Items.json", Crypter.Encrypt(JsonConvert.SerializeObject(Items), true)); }; Messenger.Default.Register <Message>(this, OnMessage); }
/// <summary> /// Dump a packet to a decimal output /// </summary> /// <param name="buffer"></param> /// <param name="length"></param> public static void ServerDump(byte[] buffer, int length) { byte serverKey = 56; buffer = Crypter.DecodeString(buffer, serverKey); if (buffer[2] == 0x2a) { serverKey = buffer[7]; } int dlength = buffer[0] + (buffer[1] << 8) - 3; byte type = buffer[2]; //if(Utils.ServerFilter(type)) //{ // ServerConsole.WriteLine("--[ SERVER: Id: {0:x2} Length: {1} ]--", type, length); // ServerConsole.Write("Decimal: "); // for(int i=0;i<length;i++) { // ServerConsole.Write("{0} ", buffer[i]); // } // ServerConsole.WriteLine(System.Environment.NewLine); //} }
public void Connect(string account, string password) { if (CurrentLoginStep == LoginStep.Connecting) { return; } Account = account; Password = password; // Save credentials to config file if (Engine.GlobalSettings.SaveAccount) { Engine.GlobalSettings.Username = Account; Engine.GlobalSettings.Password = Crypter.Encrypt(Password); Engine.GlobalSettings.Save(); } Log.Message(LogTypes.Trace, $"Start login to: {Engine.GlobalSettings.IP},{Engine.GlobalSettings.Port}"); NetClient.LoginSocket.Connect(Engine.GlobalSettings.IP, Engine.GlobalSettings.Port); CurrentLoginStep = LoginStep.Connecting; }
/// <inheritdoc/> public override void Serialize(FRWriter writer) { writer.ItemName = ClassName; if (Name != "") { writer.WriteStr("Name", Name); } if (Restrictions != Restrictions.None) { writer.WriteValue("Restrictions", Restrictions); } if (!String.IsNullOrEmpty(ConnectionString)) { writer.WriteStr("ConnectionString", Crypter.EncryptString(ConnectionString)); } if (!String.IsNullOrEmpty(ConnectionStringExpression)) { writer.WriteStr("ConnectionStringExpression", ConnectionStringExpression); } if (LoginPrompt) { writer.WriteBool("LoginPrompt", true); } if (CommandTimeout != 30) { writer.WriteInt("CommandTimeout", CommandTimeout); } if (writer.SaveChildren) { foreach (TableDataSource c in Tables) { if (c.Enabled) { writer.Write(c); } } } }
/// <summary> /// /// </summary> /// <returns></returns> public TaskResult Simulate() { var username = Crypter.DecryptString(_transactionParameter.LoginCredential.Username, PasswordPhrase); var usernameTokens = username.Split('-'); var password = Crypter.DecryptString(_transactionParameter.LoginCredential.Password, PasswordPhrase); _webDriver.FindElement(By.Name(Constants.User1TextboxName)).SendKeys(usernameTokens[0]); _webDriver.FindElement(By.Name(Constants.User2TextboxName)).SendKeys(usernameTokens[1]); _webDriver.FindElement(By.Name(Constants.PasswordTextboxName)).SendKeys(password); _webDriver.FindElement(By.CssSelector(Constants.SubmitButtonSelector)).Click(); var webDriverWait = new WebDriverWait(_webDriver, TimeSpan.FromSeconds(10)); webDriverWait.Until(d => { Logger.Info($"checking if url {d.Url.ToLower()} contains {Constants.HomePageLikeUrl.ToLower()}"); return(d.Url.ToLower().Contains(Constants.HomePageLikeUrl.ToLower())); }); return(new TaskResult { IsSuccessful = true }); }
public void TestCryptedKey() { var basePath = Util.TestDataPath(TEST_DATA, ""); var keyPath = Path.Combine(basePath, "aes"); var webKeyPath = TEST_WEBDATA + "aes-crypted/"; WebBase64 ciphertext; using (var keyDecrypter = new Crypter(keyPath)) { using (var dataEncrypter = new Encrypter(new EncryptedKeySet(new WebKeySet(webKeyPath), keyDecrypter))) { ciphertext = dataEncrypter.Encrypt(input); } using (var dataDecrypter = new Crypter(new EncryptedKeySet(new WebKeySet(webKeyPath), keyDecrypter))) { var plaintext = dataDecrypter.Decrypt(ciphertext); Expect(plaintext, Is.EqualTo(input)); } } }
public bool RecuperarSenha(RecuperarSenhaViewModel vm) { using (DbSenaiContext ctx = new DbSenaiContext()) { try { var usuario = ctx.Usuario.FirstOrDefault(u => u.Email == vm.Email && u.PerguntaSeguranca == vm.Pergunta && u.RespostaSeguranca == vm.Resposta); if (usuario == null) { return(false); } usuario.Senha = Crypter.Criptografador(vm.NovaSenha); ctx.Update(usuario); ctx.SaveChanges(); return(true); } catch (Exception) { return(false); } } }
public IActionResult Create(UserModel userModel) { try { if (ModelState.IsValid) { #region valida e-mail cadastrado var isValid = false; _db.DbUser.FindFromLogin(userModel.login, out isValid); if (!isValid) { TempData[OperationResult.Error.ToString()] = "Já existe um usuário cadastrado com este e-mail!"; return(View(userModel)); } #endregion userModel.password = Crypter.GetMD5(userModel.password); var user = _mapper.Map <User>(userModel); _db.DbUser.Insert(user); return(RedirectToAction("Index", new { message = "Usuário salvo com sucesso!", status = OperationResult.Success })); } else { TempData[OperationResult.Error.ToString()] = "Por favor preencha todos os campos obrigatórios!"; return(View(userModel)); } } catch (Exception e) { Logger.SaveLog(e, _configuration); TempData[OperationResult.Error.ToString()] = "Erro ao salvar usuário"; return(View(userModel)); } }
public void CreateAndCrypted(string keyType, string topDir, string subDir) { KeyType type = keyType; var kspath = Util.TestDataPath(WRITE_DATA, topDir, subDir); var writer = new FileSystemKeySetWriter(kspath, overwrite: true); using (var ks = CreateNewKeySet(type.Kind, KeyPurpose.DecryptAndEncrypt)) { var success = ks.Save(writer); Expect(success, Is.True); } HelperCryptCreate(writer, new FileSystemKeySet(kspath), kspath, type); var kscryptpath = Util.TestDataPath(WRITE_DATA, topDir + "-crypted", subDir); var baseWriter = new FileSystemKeySetWriter(kscryptpath, overwrite: true); using (var ks = CreateNewKeySet(type.Kind, KeyPurpose.DecryptAndEncrypt)) { var success = ks.Save(baseWriter); Expect(success, Is.True); } using (var encrypter = new Crypter(kspath)) { var cryptedwriter = new EncryptedKeySetWriter(baseWriter, encrypter); using (var eks = KeySet.LayerSecurity(FileSystemKeySet.Creator(kscryptpath), EncryptedKeySet.Creator(encrypter))) { HelperCryptCreate(cryptedwriter, eks, kscryptpath, type, new FileSystemKeySet(kscryptpath), baseWriter); } } }
public IActionResult CadastrarEmpresa(CadastrarEmpresaViewModel empresa) { try { if (empresa.CaminhoImagem == null || empresa.CaminhoImagem.Length <= 2) { empresa.CaminhoImagem = "Teste.webp"; } VerificacaoViewModel vm = new VerificacaoViewModel() { Email = empresa.Email, RazaoSocial = empresa.RazaoSocial, NomeFantasia = empresa.NomeFantasia, Cnpj = empresa.Cnpj }; var Response = usuarioRepository.VerificarSeCredencialJaFoiCadastrada(vm); if (Response == null) { empresa.Senha = Crypter.Criptografador(empresa.Senha); if (usuarioRepository.CadastrarEmpresa(empresa)) { return(Ok("Nova empresa cadastrada com sucesso!")); } else { return(BadRequest("Um erro ocorreu e nao foi possivel efetuar o cadastro.")); } } else { return(BadRequest(Response)); } } catch (Exception e) { return(BadRequest("Uma exceção ocorreu. Tente novamente.")); } }
public void CreateNoPrimary() { using (var writer = CreateNewStorageWriter(DefaultContainer, "no-primary")) using (var ks = CreateNewKeySetMeta(KeyKind.Symmetric, KeyPurpose.DecryptAndEncrypt)) { int ver = ks.AddKey(KeyStatus.Primary); Expect(ver, Is.EqualTo(1)); var success = ks.Save(writer); Expect(success, Is.True); } WebBase64 cipherText = null; using (var origKs = new StorageKeySet(GetClientCred(), DefaultContainer, "no-primary")) using (var encrypter = new Encrypter(origKs)) { cipherText = encrypter.Encrypt(Input); } using (var origKs = new StorageKeySet(GetClientCred(), DefaultContainer, "no-primary")) using (var ks = new MutableKeySet(origKs)) using (var writer = CreateNewStorageWriter(DefaultContainer, "no-primary")) { var status = ks.Demote(1); Expect(status, Is.EqualTo(KeyStatus.Active)); var success = ks.Save(writer); Expect(success, Is.True); } using (var origKs = new StorageKeySet(GetClientCred(), DefaultContainer, "no-primary")) using (var crypter = new Crypter(origKs)) { var output = crypter.Decrypt(cipherText); Expect(output, Is.EqualTo(Input)); } }
public override void Load() { base.Load(); //Engine.FpsLimit = Settings.GlobalSettings.MaxLoginFPS; UIManager.Add(new LoginBackground()); UIManager.Add(_currentGump = new LoginGump()); // Registering Packet Events NetClient.PacketReceived += NetClient_PacketReceived; NetClient.Socket.Disconnected += NetClient_Disconnected; NetClient.LoginSocket.Connected += NetClient_Connected; NetClient.LoginSocket.Disconnected += Login_NetClient_Disconnected; int music = Client.Version >= ClientVersion.CV_7000 ? 78 : Client.Version > ClientVersion.CV_308Z ? 0 : 8; Audio.PlayMusic(music); if (((Settings.GlobalSettings.AutoLogin || Reconnect) && (CurrentLoginStep != LoginSteps.Main)) || CUOEnviroment.SkipLoginScreen) { if (!string.IsNullOrEmpty(Settings.GlobalSettings.Username)) { // disable if it's the 2nd attempt CUOEnviroment.SkipLoginScreen = false; Connect(Settings.GlobalSettings.Username, Crypter.Decrypt(Settings.GlobalSettings.Password)); } } if (Client.Game.IsWindowMaximized()) { Client.Game.RestoreWindow(); } Client.Game.SetWindowSize(640, 480); //Client.Client.SetWindowPositionBySettings(); }
/// <summary> /// Comprovar si las credenciales del usuario son correctas! /// </summary> /// <param name="user"></param> /// <returns></returns> public Boolean mysqlLogin(usuari user) { //Creem la conexio a la base de dades //Obrim la conexio try { conectar.Open(); //Executem la comanda per agafar la contrasenya del usuari introduit. MySqlCommand comandom = new MySqlCommand("Select clave from usuarios where usuario='" + user.Usuario + "'", conectar); //Convertim el objecte MySqlCommand a String. string contrasenaEncriptada = comandom.ExecuteScalar().ToString(); //Comprova si la contrasenya es correcte. bool matches = Crypter.CheckPassword(user.Clave, contrasenaEncriptada); if (matches) { //Si la contrasenya es correcte. conectar.Close(); //tanquem conexio a la bbdd return(true); } else { //Si la contrasenya es incorrecte. conectar.Close(); //tanquem conexio a la bbdd return(false); } } catch { conectar.Close(); logs.Save("Error al consultar datos login en la BBDD!", 10); return(false); } }
public override void Load() { base.Load(); Engine.FpsLimit = Engine.GlobalSettings.MaxLoginFPS; Engine.UI.Add(new LoginBackground()); Engine.UI.Add(_currentGump = new LoginGump()); // Registering Packet Events NetClient.PacketReceived += NetClient_PacketReceived; NetClient.Socket.Disconnected += NetClient_Disconnected; NetClient.LoginSocket.Connected += NetClient_Connected; NetClient.LoginSocket.Disconnected += Login_NetClient_Disconnected; string[] parts = Engine.GlobalSettings.ClientVersion.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); _clientVersionBuffer = new[] { byte.Parse(parts[0]), byte.Parse(parts[1]), byte.Parse(parts[2]), byte.Parse(parts[3]) }; int music = FileManager.ClientVersion >= ClientVersions.CV_7000 ? 78 : FileManager.ClientVersion > ClientVersions.CV_308Z ? 0 : 8; Audio.PlayMusic(music); if (Engine.GlobalSettings.AutoLogin && _isFirstLogin && CurrentLoginStep != LoginStep.Main) { if (!string.IsNullOrEmpty(Engine.GlobalSettings.Username)) { Connect(Engine.GlobalSettings.Username, Crypter.Decrypt(Engine.GlobalSettings.Password)); } } }
/// <summary> /// Updates the user from the form. /// </summary> public bool Update(User user) { AutoNavigate = false; // Get the original user data User originalUser = RetrieveStrategy.New <User>().Retrieve <User>("ID", user.ID); // If the password wasn't added then reset it if (user.Password == null || user.Password == String.Empty) { user.Password = originalUser.Password; } else { user.Password = Crypter.EncryptPassword(user.Password); } bool success = base.Update(user); // If the current user edited their username then fix their authentication session if (originalUser.Username == AuthenticationState.Username && user.Username != AuthenticationState.Username) { AuthenticationState.Username = user.Username; } Result.Display(IsSelf ? Properties.Language.YourAccountUpdated : Properties.Language.UserUpdated); if (success) { NavigateAfterUpdate(); } return(success); }
/// <summary> /// Authenticate an user /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns>The logged in user object or null if the username /// or the password was wrong</returns> public User AuthenticateUser(string username, string password) { if (username == string.Empty || password == string.Empty) { return(null); } using (var connection = GetConnection()) { using (var cmd = new MySqlCommand("SELECT * FROM users WHERE username = @username ") { Connection = connection }) { cmd.Parameters.AddWithValue("@username", username); using (var reader = cmd.ExecuteReader()) { if (reader.Read() && reader.HasRows) { if (Crypter.CheckPassword(password, reader["password"].ToString())) { var groupRole = (GroupRole)Enum.Parse(typeof(GroupRole), reader["groupid"].ToString()); return(new User(reader["UserName"].ToString(), (int)reader["id"]) { GroupRole = groupRole, IsAuthenticated = groupRole > GroupRole.Guest, CreatorId = (int)reader["creatorid"] }); } } } } } return(null); }
public uint Encrypt(byte[] src, int offset, uint seqBlock, uint seqSnd) { uint dest = 0; if (seqBlock != 0) { uint block = seqBlock / 10; while (block != 0) { block = seqBlock / 10; dest = 10 * block; Crypter crypt = aEncrypt[seqBlock % 10]; if (crypt != null) { crypt.Encrypt(src, offset, seqSnd); } seqBlock = block; } } return(dest); }
public bool Decrypt(byte[] src, int offset, uint seqBlock, uint seqRcv) { if (seqBlock != 0) { uint block = 0; while (seqBlock > 0) { block = seqBlock + 10 * (block - seqBlock / 10); seqBlock /= 10; } if (block != 0) { uint dest; while (block > 0) { dest = block / 10; Crypter crypt = aEncrypt[block % 10]; if (crypt != null) { if (crypt.Decrypt(src, offset, seqRcv) == 0) { return(false); } } block = dest; } return(true); } } return(true); }
private static IdentityInfo AuthCheckingOfDefault(string userAccount, string loginPassword) { UserInfoService service = new UserInfoService(); UserInfo accountInfo = service.GetUserInfoByMobile(userAccount); if (accountInfo == null) { throw new ApiException(15023, "用户名不存在或密码错误"); } if (accountInfo.Password.StartsWith("$2y")) { if (!Crypter.CheckPassword(loginPassword, accountInfo.Password)) { throw new ApiException(15023, "用户名不存在或密码错误"); } if (Tool.GetMD5(loginPassword) != accountInfo.Password) { throw new ApiException(15023, "用户名不存在或密码错误"); } //if (HashHelper.Encrypt(HashCryptoType.MD5, loginPassword, "") != accountInfo.Password) //{ // throw new ApiException(15023, "用户名不存在或密码错误"); //} } IdentityInfo info = accountInfo.ToIdentityInfo(); if (info != null) { //TODO:查询第三方绑定信息 } return(info); }
/// <summary> /// 设置密码 /// </summary> /// <param name="reqDto"></param> /// <param name="userId"></param> /// <returns></returns> public ApiResult SetPassword(SetPasswordReqDto reqDto, long userId) { var userInfo = Util.GetEntityById <UserInfo>((int)userId); if (userInfo.Password.StartsWith("$2y")) { if (!Crypter.CheckPassword(reqDto.OldPassword, userInfo.Password)) { return(new ApiResult(15023, "旧密码不正确")); } } else { if (Tool.GetMD5(reqDto.OldPassword) != userInfo.Password) { return(new ApiResult(15023, "旧密码不正确")); } } string password = Tool.GetMD5(reqDto.Password); string sql = "update dbo.userInfo set [Password]=@Password where Id=@UserId"; var sqlParameter = new[] { new SqlParameter("@Password", password), new SqlParameter("@UserId", userId), }; int count = SqlHelper.ExecuteNonQuery(sql, sqlParameter); if (count < 1) { return(new ApiResult(11001, "设置失败")); } return(new ApiResult()); }
/// <summary> /// Encrypts the key data. /// </summary> /// <param name="key">The key.</param> /// <param name="passwordPrompt">The password prompt.</param> /// <param name="iterationCount">The interation count.</param> /// <returns></returns> public static PbeKeyStore EncryptKeyData(byte[] key, Func<string> passwordPrompt, int iterationCount) { var pks = new PbeKeyStore() { Cipher = PbeKeyType.Aes128, Hmac = PbeHashType.HmacSha1, IterationCount = iterationCount, Salt = new byte[16] }; Secure.Random.NextBytes(pks.Salt); var pbeKey = new PbeAesKey() {Size = 128}; pbeKey.AesKeyBytes = pks.GetDerivedBytes(pbeKey.Size/8, passwordPrompt); pks.IV = pbeKey.IV; using (pbeKey) using (var ks = new ImportedKeySet(pbeKey, KeyPurpose.DecryptAndEncrypt, "Pbe key")) using (var crypter = new Crypter(ks)) { var data = crypter.Encrypt(key); byte[] justciphertext = new byte[data.Length - Keyczar.HeaderLength]; Array.Copy(data, Keyczar.HeaderLength, justciphertext, 0, justciphertext.Length); pks.Key = justciphertext; } return pks; }
/// <summary> /// Decrypts the key data. /// </summary> /// <param name="passwordPrompt">The passsword prompt.</param> /// <returns></returns> public byte[] DecryptKeyData(Func<string> passwordPrompt) { var key = new PbeAesKey {IV = IV}; if (Cipher == PbeKeyType.Aes128) { key.Size = 128; } else { throw new InvalidKeySetException("Unknown Pbe Cipher"); } key.AesKeyBytes = GetDerivedBytes(key.Size/8, passwordPrompt); using (key) using (var ks = new ImportedKeySet(key, KeyPurpose.DecryptAndEncrypt, "Pbe key")) using (var crypter = new Crypter(ks)) using (var memstream = new MemoryStream()) { memstream.Write(Keyczar.FormatBytes, 0, Keyczar.FormatBytes.Length); memstream.Write(new byte[Keyczar.KeyHashLength], 0, Keyczar.KeyHashLength); memstream.Write(Key, 0, Key.Length); return crypter.Decrypt(memstream.ToArray()); } }