gpt4 book ai didi

c# - 绑定(bind) PasswordBox 密码是个坏主意吗?

转载 作者:可可西里 更新时间:2023-11-01 08:47:21 24 4
gpt4 key购买 nike

我读到 WPF PasswordBox 中的密码没有用于绑定(bind)密码的依赖属性出于安全原因。尽管如此,还是有ways to bind it anyway .

MVVM 模式的用户需要这种数据绑定(bind); viewmodel 不能在不破坏模式的情况下直接接触 PasswordBox。在 MVVM 设置中使用 PasswordBoxes 的一种方法是 pass the entire PasswordBox control到 ViewModel,但这无论如何都会打破模式。绑定(bind)密码可能是使用 MVVM 处理密码的最干净的方法。

有一个argument against binding the Password因为这会将明文密码保存在未加密的内存中,直到它被垃圾收集。然而,我的看法是,从您访问 Password 属性的那一刻起,密码无论如何都会存储在未加密的内存中。此观点(或类似观点)似乎在 this question 中得到支持.当然,它会在没有绑定(bind)的情况下在内存中停留更短的时间(并不是说登录表单有长期存在的趋势),但风险仍然存在。

鉴于这些论点,绑定(bind)密码真的是个坏主意吗?为什么?

最佳答案

使用 WPF Inspector 或 Snoop 等工具,您可以窥探密码字符串。将 PasswordBox 传递给 View 模型的另一种方法是将 Behavior 对象附加到您的 PasswordBox 对象,如下所示:

public sealed class PasswordBoxBehavior : Behavior<UIElement>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.LostKeyboardFocus += AssociatedObjectLostKeyboardFocus;
}

protected override void OnDetaching()
{
AssociatedObject.LostKeyboardFocus -= AssociatedObjectLostKeyboardFocus;
base.OnDetaching();
}

void AssociatedObjectLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var associatedPasswordBox = AssociatedObject as PasswordBox;
if (associatedPasswordBox != null)
{
// Set your view-model's Password property here
}
}
}

和 XAML 代码:

<Window ...
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">
...
<PasswordBox ....>
<i:Interaction.Behaviors>
<local:PasswordBoxBehavior />
</i:Interaction.Behaviors>
</PasswordBox>
...
</Window>

关于c# - 绑定(bind) PasswordBox 密码是个坏主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23031549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com