简体   繁体   中英

C# SecureString Usage From COM DLL

I'm trying to fix some Fortify errors. A class in my code () stores the password in a string.

 public class Foo: IDisposable
 {
 public string Password
  {
     get;
     set;
  }
 }

Fortify recommended that I should change the string to SecureString. That fixes the Fortify issue but after this I am unable to use this create the COM Object.

I would define the class like this:

[ComVisible(true)]
public class TestSecureString : IUnsecurePassword
{
    public SecureString Password
    {
        get;
        set;
    }

    string IUnsecurePassword.Password
    {
        get
        {
            if (Password == null)
                return null;

            IntPtr ptr = Marshal.SecureStringToBSTR(Password);
            string bstr = Marshal.PtrToStringBSTR(ptr);
            Marshal.ZeroFreeBSTR(ptr);
            return bstr;
        }
        set
        {
            if (value == null)
            {
                Password = null;
                return;
            }

            Password = new SecureString();
            foreach (char c in value)
            {
                Password.AppendChar(c);
            }
        }
    }
}

[ComVisible(true)]
public interface IUnsecurePassword
{
    string Password { get; set; }
}

Then in C++, the IUnsecurePassword interface would be exported like this:

  virtual HRESULT __stdcall get_Password (/*[out,retval]*/ BSTR * pRetVal ) = 0;
  virtual HRESULT __stdcall put_Password (/*[in]*/ BSTR pRetVal ) = 0;

It does not prevent someone from using the IUnsecurePassword interface if he really wants to, but it raises the bar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM