2012-03-16 69 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