如果您想提高安全意识(就像您看起来那样),那么我建议SecureString
在System.Security
命名空间中。它将字符串的内容加密保存在内存中。
你仍然可以拥有这样的属性:
SecureString password;
public string Password
{
internal get { return password.ConvertToInsecureString(); }
set { password = value.ConvertToSecureString();
}
你需要这个扩展方法类:
using System.Runtime.InteropServices; // For Marshal static class
using System.Security; // For SecureString class
public static class SecureStringExtender
{
public static SecureString ConvertToSecureString(this string text)
{
if (text == null)
throw new ArgumentNullException("text");
var secureString = new SecureString();
foreach(var c in text)
secureString.AppendChar(c);
secureString.MakeReadOnly();
return secureString;
}
public static string ConvertToInsecureString(this SecureString secureString)
{
if (secureString == null)
throw new ArgumentNullException("secureString");
IntPtr unmanagedString = IntPtr.Zero;
try
{
unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString);
return Marshal.PtrToStringUni(unmanagedString);
}
finally
{
// Zero out the sensitive text in memory for security purposes.
Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
}
}
}