当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Deleting content of String

问题描述:

I would like to remove a String from the memory of .NET application.

Lets say we have a Decryption method, which comes from a 3rd party lib and it returns a String. This is not smart, but there is nothing I can do about it.

String s = SomeComponent.Decrypt("cypherstring")

Now I would copy the content of s into a SecureString to work with. But... how do I get rid of s. I know the GC would collect it here, but if I used that string for a while it would stay. Also I would like to not rely on the GC here, since it might be security related - which requries my code to be deterministic.

My Idea is something like that:

public static SecureString Convert(ref String s)

{

//copy content of s into SecureString

//shred s

}

There is no big deal to copy the data into the SecureString, but how do I "destroy" s?

网友答案:

Use this code:

public static SecureString Convert(ref String s)
{
    //copy content of s into SecureString
    SecureString secureString;
    unsafe
    {
        fixed (char* charArray = s.ToArray())
            secureString = new SecureString(charArray, s.Length);
    }            
    //shred s
    s = null;
    GC.Collect();
    return secureString;
}

Note that the length if string cannot exceeds maximum capacity of SecureString. Maximum capacity of SecureString is 65536

分享给朋友:
您可能感兴趣的文章:
随机阅读: