簡體   English   中英

將輸入字段中的安全字符串與 c# 中的數據庫進行比較

[英]Comparing securestring from inputfield with database in c#

XMAL

<PasswordBox PasswordChar="*" PasswordChanged="PasswordBox_PasswordChanged" Background="#545d6a" Foreground="White" FontSize="18"/>

背后的代碼

private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
    {
        if (this.DataContext != null)
        { ((dynamic)this.DataContext).SecurePassword = ((PasswordBox)sender).SecurePassword; }
    }

我有一個 class Klant,其屬性為 Paswood,我想與 SecureString 進行比較。

視圖模型

public SecureString SecurePassword { private get; set; }

Klant = DataBaseOperations.OphalenKlantViaUsername(UserName);
            if (Klant != null)
            {
                if (Klant.Paswoord == SecurePassword.ToString())
                {
                    the password is correct and the program continues
                }
                else
                {
                    MessageBox.Show("the password is incorrect");
                }
            }
            else
            {
                User does not exist.
            }

有人可以幫助我嗎?

您當前正在將密碼的相等性與SecureString class 的字符串表示形式進行比較。 SecureString.ToString不會將安全密碼作為字符串返回。 您將必須顯式轉換它:

private bool IsPasswordValid(SecureString referencePassword, SecureString password)
{
  IntPtr valuePtr = IntPtr.Zero;
  try
  {
    valuePtr = Marshal.SecureStringToGlobalAllocUnicode(password);
    string plainTextPassword = Marshal.PtrToStringUni(valuePtr);

    valuePtr = Marshal.SecureStringToGlobalAllocUnicode(referencePassword);
    string plainTextReferencePassword = Marshal.PtrToStringUni(valuePtr);

    return plainTextReferencePassword.Equals(plainTextPassword, StringComparison.Ordinal);
  } 
  finally 
  {
    Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
  }
}

用法

if (IsPasswordValid(Klant.Paswoord, this.SecurePassword)
{
  // Password is valid
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM