1

proxy.exe我通过以下方式创建一个安全字符串:

public SecureString GetSecureEncryptionKey()
    {
        string strPassword = "8charPwd";
        SecureString secureStr = new SecureString();
        if (strPassword.Length > 0)
        {
            foreach (var c in strPassword.ToCharArray()) secureStr.AppendChar(c);
        }
        return secureStr;
    }

然后在main.exe我使用这个函数解密它:

public string convertToUNSecureString(SecureString secstrPassword)
    {
        IntPtr unmanagedString = IntPtr.Zero;
        try
        {
            unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secstrPassword);
            return Marshal.PtrToStringUni(unmanagedString);
        }
        finally
        {
            Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
        }
    }

问题是返回的字符串是空的,除非我在main.exe中加密了初始字符串,否则返回的解密字符串确实是“8charPwd”。为什么会这样?SecureString 加密是否绑定到可执行文件?

4

1 回答 1

6

The purpose of SecureString is to keep strings safety inside your application memory(keep the string secure in RAM) SecureString object is not a serialize-able. You cannot transfer an instance between applications.

SecureString encrypt the string by using RtlEncryptMemory (WINAPI) with the flag:"0" (only the same process can decrypt the content). RtlEncryptMemory API

if you don't want to expose the password(at any time) in the RAM, you can create a simple obfuscation(or encryption) logic, and then transfer the content.

Edit:

I found 2 old questions that might be helpful for you:

When would I need a SecureString in .NET?

Wcf-Authentication and Logging

于 2015-02-14T15:09:15.800 回答