检索SecureString值的最佳方法

时间:2012-01-25 20:25:43

标签: .net post securestring

我正在尝试构建一个自动化工具,它会检查我支票账户上的最近交易(监视我妻子的购买情况)。该工具通过SSL发布我的用户名和密码,然后抓取银行页面内容进行交易。当然,所有内容都通过SSL发送,但为了使其自动化,我需要在某处存储我的银行用户名和密码。

所以我开始研究.NET字符串,安全性和SecureString的漏洞。我创建了一个表单,将我的用户名和密码输入SecureString(逐个字符),确保不使用任何System.String。然后我从SecureString中检索一个char [],从中获取一个byte [],将char [0置零,使用DPAPI加密byte []并使用代码内置的salt字符串,将加密的byte []转换为Base64 System.String,将byte []置零,并将加密字符串保存到应用程序设置。

问题是,如何让我在HttpWebRequest中将其恢复为POST数据而不使其成为System.String。我想出的是以下函数(也是URL编码字符而不创建字符串)。

/// <summary>
/// Retrieves, (and then zero's,) a character array from the SecureString.
/// Then optionally URL encodes the characters and returns an encoded byte array.
/// Make sure to zero out the byte array when you're done with it.
/// </summary>
/// <param name="secure">The SecureString to be retrieved.</param>
/// <param name="encodingFormat">The encoding format used to retrieve the byte array. The default is UTF-8.</param>
/// <param name="urlEncode">If true will URL encode characters which are invalid for URL's.</param>
/// <returns></returns>
public static byte[] ToByteArray(this SecureString secure, System.Text.Encoding encodingFormat, bool urlEncode)
{
    if (secure == null) throw new ArgumentNullException("secure");

    if (encodingFormat == null)
        encodingFormat = System.Text.Encoding.UTF8;

    char[] chars = new char[secure.Length];
    byte[] bytesToReturn;

    // copy the SecureString data into an unmanaged char array and get a pointer to it
    IntPtr ptr = Marshal.SecureStringToCoTaskMemUnicode(secure);

    try
    {
        // copy the unmanaged char array into a managed char array
        Marshal.Copy(ptr, chars, 0, secure.Length);
    }
    finally
    {
        Marshal.ZeroFreeCoTaskMemUnicode(ptr);
    }

    if (false == urlEncode)
    {
        bytesToReturn = encodingFormat.GetBytes(chars);
    }
    else
    {
        List<int> unsafeUrlCharIntValues = new List<int>();
        unsafeUrlCharIntValues.AddRange(Enumerable.Range(32, 16)); //   32-47   Reserved Characters:    ' '!?#$%&'()*+,-./
        unsafeUrlCharIntValues.AddRange(Enumerable.Range(58, 7)); //    58-64   Reserved Characters:    :;<=>?@
        unsafeUrlCharIntValues.AddRange(Enumerable.Range(91, 6)); //    91-96   Reserved Characters:    [\]^_`
        unsafeUrlCharIntValues.AddRange(Enumerable.Range(123, 4)); //   123-126 Reserved Characters:    {|}~

        // Get a count of the unsafe URL characters to see if any processing is required and how many extra char's we'll need in the array.
        int unsafeCharCount = 0;
        for (int i = 0; i < chars.Length; i++)
            if (unsafeUrlCharIntValues.Contains((int)chars[i]))
                unsafeCharCount++;

        if (unsafeCharCount < 1)
        {
            bytesToReturn = encodingFormat.GetBytes(chars);
        }
        else
        {
            char[] encodedChars = EncodeChars(chars);
            bytesToReturn = encodingFormat.GetBytes(encodedChars);

            // zero out encoded chars for security
            for (int i = 0; i < encodedChars.Length; i++)
                encodedChars[i] = '\0';
        }
    }

    // zero out chars
    for (int i = 0; i < chars.Length; i++)
        chars[i] = '\0';

    return bytesToReturn;
}

在我完成它之后,我将char []清零了。在将它们写入HttpWebRequest流之后,我还确保将返回的byte []清零。这是安全的还是GC会复制char []和byte []对象?这比使用System.String更好吗?我已经阅读了其他{​​{3}}说要使用不安全的代码并在非托管内存中执行所有操作,但我仍然需要在我的HttpWebRequest中获取一个byte []。

0 个答案:

没有答案