📜  PasswordBox 助手 - C# (1)

📅  最后修改于: 2023-12-03 15:03:32.015000             🧑  作者: Mango

PasswordBox 助手 - C#

使用PasswordBox(密码框)是保护用户密码的一种有效方式。但是,开发人员又常常需要在代码中获取PasswordBox的值。为了在代码中使用PasswordBox,我们需要一个PasswordBox助手。

功能
  • 获取PasswordBox的值
  • 将PasswordBox字符串转换为SecureString
  • 将SecureString转换为字符串
用法
获取PasswordBox的值
string password = passwordBox.Password;
将PasswordBox字符串转换为SecureString
SecureString securePassword = PasswordBoxHelper.ConvertToSecureString(passwordBox.Password);
将SecureString转换为字符串
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);
        }
    }
}