2012-03-16 44 views
2

我有一个密码框,我想获取输入数据以检查验证。对变量使用密码箱的值

我passwordbox 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.This是虚拟演示,因此不需要加密。我之前使用了一个文本框,验证工作正常。使用密码b牛只是复杂的东西。

回答

2

SecureString class不允许您查看该值;这就是它的重点。如果你希望能够与进入PasswordBox价值的工作,使用PasswordBox代替SecurePassword成员的密码员:

private void loginbutton_Click(object sender, RoutedEventArgs e) 
{ 
    usr = textBox1.Text; 
    String pass = textBox2.Password; 
} 
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 

     } 
+0

它工作。非常有用的感谢 – 2016-03-18 02:20:18