使用passwordbox的值作为变量

时间:2012-03-16 04:24:55

标签: c# wpf visual-studio-2010

我有一个密码框,我想获取输入数据以检查验证。

我的密码箱c#代码

  public void textBox2_TextInput(object sender, TextCompositionEventArgs e)
    {
        //pass = textBox2.ToString();
    }

和xaml代码

<PasswordBox Name="textBox2" 
             PasswordChar="*"  
             TextInput="textBox2_TextInput" />

这是我为捕获密码所写的内容

  private void loginbutton_Click(object sender, RoutedEventArgs e)
   {
       usr = textBox1.Text;
       SecureString passdat =textBox2.SecurePassword;
       pass = passdat.ToString();
   }             

它返回null。这是一个虚拟演示,因此不需要加密。我之前使用的是文本框,验证工作正常。使用密码框只是复杂的事情。

2 个答案:

答案 0 :(得分:2)

SecureString class不允许您查看该值;这就是它的重点。如果您希望能够使用输入到PasswordBox中的值,请使用PasswordBox的密码成员而不是SecurePassword成员:

private void loginbutton_Click(object sender, RoutedEventArgs e)
{
    usr = textBox1.Text;
    String pass = textBox2.Password;
}

答案 1 :(得分:2)

请注意,SecureString没有检查,比较或转换SecureString值的成员。缺少此类成员有助于保护实例的价值免受意外或恶意暴露。使用System.Runtime.InteropServices.Marshal类的适当成员(例如SecureStringToBSTR方法)来操作SecureString对象的值。

        private void loginbutton_Click(object sender, RoutedEventArgs e)
        {
            usr = textBox1.Text;
            txtPassword=textBox2.Text;

            SecureString objSecureString=new SecureString();
            char[] passwordChar = txtPassword.ToCharArray();
            foreach (char c in passwordChar)
                    objSecureString.AppendChar(c);
            objSecureString.MakeReadOnly();//Notice at the end that the MakeReadOnly command prevents the SecureString to be edited any further.


            //Reading a SecureString is more complicated. There is no simple ToString method, which is also intended to keep the data secure. To read the data C# developers must access the data in memory directly. Luckily the .NET Framework makes it fairly simple:
            IntPtr stringPointer = Marshal.SecureStringToBSTR(objSecureString);
            string normalString = Marshal.PtrToStringBSTR(stringPointer);//Original Password text

        }