我需要将base64编码的字符串转换为SecureString,而不必使用常规的C#字符串,以防止密码以明文形式存储在内存中。
现在我有执行此操作的代码:
string encodedPassword = "TXlQYXNzd29yZA==";
byte[] encodedBytes = Convert.FromBase64String(encodedPassword);
string clearTextPassword = Encoding.UTF8.GetString(encodedBytes);
SecureString secureString = ConvertToSecureString(clearTextPassword);
我想要这样的东西: Convert.FromBase64StringToSecureString(EncodedPassword)
答案 0 :(得分:0)
我最终编写了以下使用GetChars()方法的方法,然后在使用后清除数组。如果在执行过程中引发异常,则有可能在内存中留下一些东西,但我并不担心这种情况。
private static SecureString DecodeBase64String(string encodedData)
{
var secureString = new SecureString();
if (string.IsNullOrWhiteSpace(encodedData))
{
secureString.MakeReadOnly();
return secureString;
}
try
{
var encodedBytes = Convert.FromBase64String(encodedData);
var passwordChars = Encoding.UTF8.GetChars(encodedBytes);
// clear the encoded bytes so they aren't resident in memory
for (var i = 0; i < encodedBytes.Length; i++)
{
encodedBytes[i] = 0;
}
foreach (var c in passwordChars)
{
secureString.AppendChar(c);
}
// clear the password characters so they aren't resident in memory
for (var i = 0; i < passwordChars.Length; i++)
{
passwordChars[i] = (char)0;
}
secureString.MakeReadOnly();
return secureString;
}
catch (FormatException)
{
secureString.MakeReadOnly();
return secureString;
}
}