简体   繁体   中英

Comparing securestring from inputfield with database in c#

XMAL

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

Code behind

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

I have a class Klant with a property Paswoord that i want to compare with the secureString.

ViewModel

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.
            }

Can somebody help me?

You are currently comparing equality of the password with the string representation of the SecureString class. SecureString.ToString will not return the secured password as string. You will have to explicitly convert it:

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);
  }
}

Usage

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM