【问题标题】:How to I convert a Base64-encoded string directly to a SecureString如何将 Base64 编码的字符串直接转换为 SecureString
【发布时间】:2019-01-07 18:08:13
【问题描述】:

我需要将 base64 编码的字符串转换为 SecureString,而不必使用常规的 C# 字符串,防止密码以明文形式存储在内存中。

现在我有这样的代码:

string encodedPassword = "TXlQYXNzd29yZA==";
byte[] encodedBytes = Convert.FromBase64String(encodedPassword);
string clearTextPassword = Encoding.UTF8.GetString(encodedBytes);
SecureString secureString = ConvertToSecureString(clearTextPassword);

我想要这样的东西: Convert.FromBase64StringToSecureString(EncodedPassword)

【问题讨论】:

  • 好吧,你的 base64 表示已经存储在内存中,所以我不确定你从编码 -> SecureString 得到什么实际保护。 You may also want to take a look at this如果你打算去其他平台。
  • 我同意您关于 base64 字符串已经在内存中的评论,因此可以找到密码。我正在尝试通过以明文形式查找密码的安全测试。我知道“混淆!=安全”,但在这种情况下它会有所帮助。

标签: c# utf-8 base64 securestring


【解决方案1】:

我最终编写了以下使用 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;
    }
}

【讨论】:

    猜你喜欢
    • 2019-02-16
    • 2018-08-05
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多