📅  最后修改于: 2023-12-03 15:03:32.015000             🧑  作者: Mango
使用PasswordBox(密码框)是保护用户密码的一种有效方式。但是,开发人员又常常需要在代码中获取PasswordBox的值。为了在代码中使用PasswordBox,我们需要一个PasswordBox助手。
string password = passwordBox.Password;
SecureString securePassword = PasswordBoxHelper.ConvertToSecureString(passwordBox.Password);
string password = PasswordBoxHelper.ConvertToUnsecureString(securePassword);
using System.Security;
public static class PasswordBoxHelper
{
/// <summary>
/// 将PasswordBox中的字符串转换为SecureString
/// </summary>
public static SecureString ConvertToSecureString(string password)
{
if (password == null)
{
throw new ArgumentNullException(nameof(password));
}
var securePassword = new SecureString();
foreach (var c in password)
{
securePassword.AppendChar(c);
}
securePassword.MakeReadOnly();
return securePassword;
}
/// <summary>
/// 将SecureString转换为字符串
/// </summary>
public static string ConvertToUnsecureString(SecureString securePassword)
{
if (securePassword == null)
{
throw new ArgumentNullException(nameof(securePassword));
}
IntPtr passwordBSTR = IntPtr.Zero;
try
{
passwordBSTR = Marshal.SecureStringToBSTR(securePassword);
return Marshal.PtrToStringBSTR(passwordBSTR);
}
finally
{
Marshal.ZeroFreeBSTR(passwordBSTR);
}
}
}