C# SecureString Question

后端 未结 6 1500
忘掉有多难
忘掉有多难 2020-11-29 00:58

Is there any way to get the value of a SecureString without comprising security? For example, in the code below as soon as you do PtrToStringBSTR the string is no longer sec

6条回答
  •  迷失自我
    2020-11-29 01:56

    Here's a function that frees the native buffer as well, so you don't have the string in memory.

        protected static string ConvertToUnsecureString(SecureString securePassword)
        {
            if (securePassword == null)
                throw new ArgumentNullException("securePassword");
    
            IntPtr unmanagedString = IntPtr.Zero;
            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
                return Marshal.PtrToStringUni(unmanagedString);
            }
            finally
            {
                // Free the native buffer
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }
        }
    

    Source

提交回复
热议问题