代码之家  ›  专栏  ›  技术社区  ›  Andrew Arnott

如何将SecureString转换为System.String?

  •  129
  • Andrew Arnott  · 技术社区  · 17 年前

    所有关于通过创建System.String取消保护SecureString的保留 在一边 那怎么办呢??

    如何将普通System.Security.SecureString转换为System.String?

    我相信很多熟悉SecureString的人都会回答说,永远不要将SecureString转换为普通的.NET字符串,因为它会删除所有安全保护。 . 但现在我的程序用普通字符串做任何事情,我正在努力提高它的安全性,尽管我将使用一个API向我返回一个SecureString,但我确实是 不

    对于那些可能需要知道我为什么要这样做的人,我从一个用户那里获取一个密码,并将其作为一个html表单帖子提交,以将用户登录到一个网站。所以这实际上必须使用托管的、未加密的缓冲区来完成。如果我甚至可以访问未经管理、未加密的缓冲区,我想我可以在网络流上逐字节地写入数据流,并希望这样可以确保密码始终安全。我希望至少能找到其中一种情况的答案。

    8 回复  |  直到 9 年前
        1
  •  208
  •   Rasmus Faber    8 年前

    使用 System.Runtime.InteropServices.Marshal

    String SecureStringToString(SecureString value) {
      IntPtr valuePtr = IntPtr.Zero;
      try {
        valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
        return Marshal.PtrToStringUni(valuePtr);
      } finally {
        Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
      }
    }
    

    如果要避免创建托管字符串对象,可以使用 Marshal.ReadInt16(IntPtr, Int32) :

    void HandleSecureString(SecureString value) {
      IntPtr valuePtr = IntPtr.Zero;
      try {
        valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
        for (int i=0; i < value.Length; i++) {
          short unicodeChar = Marshal.ReadInt16(valuePtr, i*2);
          // handle unicodeChar
        }
      } finally {
        Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
      }
    }
    
        2
  •  132
  •   Steve In CO    12 年前

    显然,您知道这会破坏SecureString的全部用途,但我还是要重申一下。

    如果您想要一行程序,请尝试以下方法:(.NET 4及以上版本)

    string password = new System.Net.NetworkCredential(string.Empty, securePassword).Password;
    

    其中securePassword是一个SecureString。

        3
  •  50
  •   Andrew Arnott    17 年前

    正当 this article

    static String SecureStringToString(SecureString value)
    {
        IntPtr bstr = Marshal.SecureStringToBSTR(value);
    
        try
        {
            return Marshal.PtrToStringBSTR(bstr);
        }
        finally
        {
            Marshal.FreeBSTR(bstr);
        }
    }
    
        4
  •  18
  •   Matt    8 年前

    在我看来, 是解决这个问题的最舒适的方法。

    我拿了 Steve in CO's excellent answer

    public static class Extensions
    {
        // convert a secure string into a normal plain text string
        public static String ToPlainString(this System.Security.SecureString secureStr)
        {
            String plainStr=new System.Net.NetworkCredential(string.Empty, secureStr).Password;
            return plainStr;
        }
    
        // convert a plain text string into a secure string
        public static System.Security.SecureString ToSecureString(this String plainStr)
        {
            var secStr = new System.Security.SecureString(); secStr.Clear();
            foreach (char c in plainStr.ToCharArray())
            {
                secStr.AppendChar(c);
            }
            return secStr;
        }
    }
    

    有了这个,你现在可以 只需来回转换字符串即可

    // create a secure string
    System.Security.SecureString securePassword = "MyCleverPwd123".ToSecureString(); 
    // convert it back to plain text
    String plainPassword = securePassword.ToPlainString();  // convert back to normal string
    

    但请记住,解码方法只能用于测试。

        5
  •  15
  •   Tomas Kubes    8 年前

    我认为这对我来说是最好的 SecureString 相依函数 概括 它们在匿名函数中的依赖逻辑可以更好地控制内存中解密的字符串(一旦锁定)。

    在此代码段中解密SecureStrings的实现将:

    1. 通过 its reference 到Func/Action委托。
    2. finally 块

    这显然使“标准化”和维护呼叫者比依赖不太理想的替代方案容易得多:

    • 从文件返回已解密的字符串 string DecryptSecureString(...) 辅助函数。
    • 在需要的地方复制此代码。

    1. static T DecryptSecureString<T> 它允许您访问 Func 来自调用方的委托(如 DecryptSecureStringWithFunc
    2. static void DecryptSecureString 只是一个“无效”版本,使用 Action 在您实际上不想/不需要返回任何内容的情况下委派(如 DecryptSecureStringWithAction 试验方法)。

    这两种用法的示例可在中找到 StringsTest

    Strings.cs

    using System;
    using System.Runtime.InteropServices;
    using System.Security;
    
    namespace SecurityUtils
    {
        public partial class Strings
        {
            /// <summary>
            /// Passes decrypted password String pinned in memory to Func delegate scrubbed on return.
            /// </summary>
            /// <typeparam name="T">Generic type returned by Func delegate</typeparam>
            /// <param name="action">Func delegate which will receive the decrypted password pinned in memory as a String object</param>
            /// <returns>Result of Func delegate</returns>
            public static T DecryptSecureString<T>(SecureString secureString, Func<string, T> action)
            {
                var insecureStringPointer = IntPtr.Zero;
                var insecureString = String.Empty;
                var gcHandler = GCHandle.Alloc(insecureString, GCHandleType.Pinned);
    
                try
                {
                    insecureStringPointer = Marshal.SecureStringToGlobalAllocUnicode(secureString);
                    insecureString = Marshal.PtrToStringUni(insecureStringPointer);
    
                    return action(insecureString);
                }
                finally
                {
                    //clear memory immediately - don't wait for garbage collector
                    fixed(char* ptr = insecureString )
                    {
                        for(int i = 0; i < insecureString.Length; i++)
                        {
                            ptr[i] = '\0';
                        }
                    }
    
                    insecureString = null;
    
                    gcHandler.Free();
                    Marshal.ZeroFreeGlobalAllocUnicode(insecureStringPointer);
                }
            }
    
            /// <summary>
            /// Runs DecryptSecureString with support for Action to leverage void return type
            /// </summary>
            /// <param name="secureString"></param>
            /// <param name="action"></param>
            public static void DecryptSecureString(SecureString secureString, Action<string> action)
            {
                DecryptSecureString<int>(secureString, (s) =>
                {
                    action(s);
                    return 0;
                });
            }
        }
    }
    

    StringsTest.cs

    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using System.Security;
    
    namespace SecurityUtils.Test
    {
        [TestClass]
        public class StringsTest
        {
            [TestMethod]
            public void DecryptSecureStringWithFunc()
            {
                // Arrange
                var secureString = new SecureString();
    
                foreach (var c in "UserPassword123".ToCharArray())
                    secureString.AppendChar(c);
    
                secureString.MakeReadOnly();
    
                // Act
                var result = Strings.DecryptSecureString<bool>(secureString, (password) =>
                {
                    return password.Equals("UserPassword123");
                });
    
                // Assert
                Assert.IsTrue(result);
            }
    
            [TestMethod]
            public void DecryptSecureStringWithAction()
            {
                // Arrange
                var secureString = new SecureString();
    
                foreach (var c in "UserPassword123".ToCharArray())
                    secureString.AppendChar(c);
    
                secureString.MakeReadOnly();
    
                // Act
                var result = false;
    
                Strings.DecryptSecureString(secureString, (password) =>
                {
                    result = password.Equals("UserPassword123");
                });
    
                // Assert
                Assert.IsTrue(result);
            }
        }
    }
    

    [TestMethod]
    public void DecryptSecureStringWithAction()
    {
        // Arrange
        var secureString = new SecureString();
    
        foreach (var c in "UserPassword123".ToCharArray())
            secureString.AppendChar(c);
    
        secureString.MakeReadOnly();
    
        // Act
        string copyPassword = null;
    
        Strings.DecryptSecureString(secureString, (password) =>
        {
            copyPassword = password; // Please don't do this!
        });
    
        // Assert
        Assert.IsNull(copyPassword); // Fails
    }
    

    快乐编码!

        6
  •  7
  •   sclarke81    7 年前

    我基于 answer from rdev5

    我认为我的解决方案的优点是不需要不安全的代码。

    /// <summary>
    /// Allows a decrypted secure string to be used whilst minimising the exposure of the
    /// unencrypted string.
    /// </summary>
    /// <typeparam name="T">Generic type returned by Func delegate.</typeparam>
    /// <param name="secureString">The string to decrypt.</param>
    /// <param name="action">
    /// Func delegate which will receive the decrypted password as a string object
    /// </param>
    /// <returns>Result of Func delegate</returns>
    /// <remarks>
    /// This method creates an empty managed string and pins it so that the garbage collector
    /// cannot move it around and create copies. An unmanaged copy of the the secure string is
    /// then created and copied into the managed string. The action is then called using the
    /// managed string. Both the managed and unmanaged strings are then zeroed to erase their
    /// contents. The managed string is unpinned so that the garbage collector can resume normal
    /// behaviour and the unmanaged string is freed.
    /// </remarks>
    public static T UseDecryptedSecureString<T>(this SecureString secureString, Func<string, T> action)
    {
        int length = secureString.Length;
        IntPtr sourceStringPointer = IntPtr.Zero;
    
        // Create an empty string of the correct size and pin it so that the GC can't move it around.
        string insecureString = new string('\0', length);
        var insecureStringHandler = GCHandle.Alloc(insecureString, GCHandleType.Pinned);
    
        IntPtr insecureStringPointer = insecureStringHandler.AddrOfPinnedObject();
    
        try
        {
            // Create an unmanaged copy of the secure string.
            sourceStringPointer = Marshal.SecureStringToBSTR(secureString);
    
            // Use the pointers to copy from the unmanaged to managed string.
            for (int i = 0; i < secureString.Length; i++)
            {
                short unicodeChar = Marshal.ReadInt16(sourceStringPointer, i * 2);
                Marshal.WriteInt16(insecureStringPointer, i * 2, unicodeChar);
            }
    
            return action(insecureString);
        }
        finally
        {
            // Zero the managed string so that the string is erased. Then unpin it to allow the
            // GC to take over.
            Marshal.Copy(new byte[length], 0, insecureStringPointer, length);
            insecureStringHandler.Free();
    
            // Zero and free the unmanaged string.
            Marshal.ZeroFreeBSTR(sourceStringPointer);
        }
    }
    
    /// <summary>
    /// Allows a decrypted secure string to be used whilst minimising the exposure of the
    /// unencrypted string.
    /// </summary>
    /// <param name="secureString">The string to decrypt.</param>
    /// <param name="action">
    /// Func delegate which will receive the decrypted password as a string object
    /// </param>
    /// <returns>Result of Func delegate</returns>
    /// <remarks>
    /// This method creates an empty managed string and pins it so that the garbage collector
    /// cannot move it around and create copies. An unmanaged copy of the the secure string is
    /// then created and copied into the managed string. The action is then called using the
    /// managed string. Both the managed and unmanaged strings are then zeroed to erase their
    /// contents. The managed string is unpinned so that the garbage collector can resume normal
    /// behaviour and the unmanaged string is freed.
    /// </remarks>
    public static void UseDecryptedSecureString(this SecureString secureString, Action<string> action)
    {
        UseDecryptedSecureString(secureString, (s) =>
        {
            action(s);
            return 0;
        });
    }
    
        7
  •  1
  •   Eric Alexander Silveira    7 年前

    这是你想要的C代码。

    %ProjectPath%/SecureStringsEasy.cs

    using System;
    using System.Security;
    using System.Runtime.InteropServices;
    namespace SecureStringsEasy
    {
        public static class MyExtensions
        {
            public static SecureString ToSecureString(string input)
            {
                SecureString secureString = new SecureString();
                foreach (var item in input)
                {
                    secureString.AppendChar(item);
                }
                return secureString;
            }
            public static string ToNormalString(SecureString input)
            {
                IntPtr strptr = Marshal.SecureStringToBSTR(input);
                string normal = Marshal.PtrToStringBSTR(strptr);
                Marshal.ZeroFreeBSTR(strptr);
                return normal;
            }
        }
    }
    
        8
  •  1
  •   John Flaherty    7 年前

    This answer by sclarke81 . 我喜欢他的答案,我使用的是导数,但sclarke81有一个缺陷。我没有名声,所以我不能评论。这个问题似乎太小了,不需要另一个答案,我可以编辑它。所以我做了。它被拒绝了。现在我们有了另一个答案。

    sclarke81我希望你能看到这一点(最后):

    Marshal.Copy(new byte[length], 0, insecureStringPointer, length);
    

    Marshal.Copy(new byte[length * 2], 0, insecureStringPointer, length * 2);
    

    关于bug修复的完整答案:

    
        /// 
        /// Allows a decrypted secure string to be used whilst minimising the exposure of the
        /// unencrypted string.
        /// 
        /// Generic type returned by Func delegate.
        /// The string to decrypt.
        /// 
        /// Func delegate which will receive the decrypted password as a string object
        /// 
        /// Result of Func delegate
        /// 
        /// This method creates an empty managed string and pins it so that the garbage collector
        /// cannot move it around and create copies. An unmanaged copy of the the secure string is
        /// then created and copied into the managed string. The action is then called using the
        /// managed string. Both the managed and unmanaged strings are then zeroed to erase their
        /// contents. The managed string is unpinned so that the garbage collector can resume normal
        /// behaviour and the unmanaged string is freed.
        /// 
        public static T UseDecryptedSecureString(this SecureString secureString, Func action)
        {
            int length = secureString.Length;
            IntPtr sourceStringPointer = IntPtr.Zero;
    
            // Create an empty string of the correct size and pin it so that the GC can't move it around.
            string insecureString = new string('\0', length);
            var insecureStringHandler = GCHandle.Alloc(insecureString, GCHandleType.Pinned);
    
            IntPtr insecureStringPointer = insecureStringHandler.AddrOfPinnedObject();
    
            try
            {
                // Create an unmanaged copy of the secure string.
                sourceStringPointer = Marshal.SecureStringToBSTR(secureString);
    
                // Use the pointers to copy from the unmanaged to managed string.
                for (int i = 0; i < secureString.Length; i++)
                {
                    short unicodeChar = Marshal.ReadInt16(sourceStringPointer, i * 2);
                    Marshal.WriteInt16(insecureStringPointer, i * 2, unicodeChar);
                }
    
                return action(insecureString);
            }
            finally
            {
                // Zero the managed string so that the string is erased. Then unpin it to allow the
                // GC to take over.
                Marshal.Copy(new byte[length * 2], 0, insecureStringPointer, length * 2);
                insecureStringHandler.Free();
    
                // Zero and free the unmanaged string.
                Marshal.ZeroFreeBSTR(sourceStringPointer);
            }
        }
    
        /// 
        /// Allows a decrypted secure string to be used whilst minimising the exposure of the
        /// unencrypted string.
        /// 
        /// The string to decrypt.
        /// 
        /// Func delegate which will receive the decrypted password as a string object
        /// 
        /// Result of Func delegate
        /// 
        /// This method creates an empty managed string and pins it so that the garbage collector
        /// cannot move it around and create copies. An unmanaged copy of the the secure string is
        /// then created and copied into the managed string. The action is then called using the
        /// managed string. Both the managed and unmanaged strings are then zeroed to erase their
        /// contents. The managed string is unpinned so that the garbage collector can resume normal
        /// behaviour and the unmanaged string is freed.
        /// 
        public static void UseDecryptedSecureString(this SecureString secureString, Action action)
        {
            UseDecryptedSecureString(secureString, (s) =>
            {
                action(s);
                return 0;
            });
        }
    }
    
        9
  •  1
  •   Rustam Shafigullin    6 年前

    根据sclarke81解决方案和John Flaherty修复方案,最终工作方案为:

        public static class Utils
        {
            /// <remarks>
            /// This method creates an empty managed string and pins it so that the garbage collector
            /// cannot move it around and create copies. An unmanaged copy of the the secure string is
            /// then created and copied into the managed string. The action is then called using the
            /// managed string. Both the managed and unmanaged strings are then zeroed to erase their
            /// contents. The managed string is unpinned so that the garbage collector can resume normal
            /// behaviour and the unmanaged string is freed.
            /// </remarks>
            public static T UseDecryptedSecureString<T>(this SecureString secureString, Func<string, T> action)
            {
                int length = secureString.Length;
                IntPtr sourceStringPointer = IntPtr.Zero;
    
                // Create an empty string of the correct size and pin it so that the GC can't move it around.
                string insecureString = new string('\0', length);
                var insecureStringHandler = GCHandle.Alloc(insecureString, GCHandleType.Pinned);
    
                IntPtr insecureStringPointer = insecureStringHandler.AddrOfPinnedObject();
    
                try
                {
                    // Create an unmanaged copy of the secure string.
                    sourceStringPointer = Marshal.SecureStringToBSTR(secureString);
    
                    // Use the pointers to copy from the unmanaged to managed string.
                    for (int i = 0; i < secureString.Length; i++)
                    {
                        short unicodeChar = Marshal.ReadInt16(sourceStringPointer, i * 2);
                        Marshal.WriteInt16(insecureStringPointer, i * 2, unicodeChar);
                    }
    
                    return action(insecureString);
                }
                finally
                {
                    // Zero the managed string so that the string is erased. Then unpin it to allow the
                    // GC to take over.
                    Marshal.Copy(new byte[length * 2], 0, insecureStringPointer, length * 2);
                    insecureStringHandler.Free();
    
                    // Zero and free the unmanaged string.
                    Marshal.ZeroFreeBSTR(sourceStringPointer);
                }
            }
    
            /// <summary>
            /// Allows a decrypted secure string to be used whilst minimising the exposure of the
            /// unencrypted string.
            /// </summary>
            /// <param name="secureString">The string to decrypt.</param>
            /// <param name="action">
            /// Func delegate which will receive the decrypted password as a string object
            /// </param>
            /// <returns>Result of Func delegate</returns>
            /// <remarks>
            /// This method creates an empty managed string and pins it so that the garbage collector
            /// cannot move it around and create copies. An unmanaged copy of the the secure string is
            /// then created and copied into the managed string. The action is then called using the
            /// managed string. Both the managed and unmanaged strings are then zeroed to erase their
            /// contents. The managed string is unpinned so that the garbage collector can resume normal
            /// behaviour and the unmanaged string is freed.
            /// </remarks>
            public static void UseDecryptedSecureString(this SecureString secureString, Action<string> action)
            {
                UseDecryptedSecureString(secureString, (s) =>
                {
                    action(s);
                    return 0;
                });
            }
        }
    
        10
  •  1
  •   Mad Sheffie    5 年前

    被接受为答案的代码是正确的,在大多数情况下都有效,但如评论中所述,使用BSTR会更好,并涵盖所有情况:

    private string SecureStringToString(SecureString value) {
        IntPtr valuePtr = IntPtr.Zero;
        try {
            valuePtr = Marshal.SecureStringToBSTR(value);
            return Marshal.PtrToStringBSTR(valuePtr);
        } finally {
            Marshal.ZeroFreeBSTR(valuePtr);
        }
    }
    
        11
  •  -5
  •   Jesse Motes    11 年前
    // using so that Marshal doesn't have to be qualified
    using System.Runtime.InteropServices;    
    //using for SecureString
    using System.Security;
    public string DecodeSecureString (SecureString Convert) 
    {
        //convert to IntPtr using Marshal
        IntPtr cvttmpst = Marshal.SecureStringToBSTR(Convert);
        //convert to string using Marshal
        string cvtPlainPassword = Marshal.PtrToStringAuto(cvttmpst);
        //return the now plain string
        return cvtPlainPassword;
    }
    
        12
  •  -5
  •   T D Nguyen    10 年前

    如果你使用 StringBuilder 而不是 string ,您可以在完成时覆盖内存中的实际值。这样,在垃圾收集收集到密码之前,密码不会挂在内存中。

    StringBuilder.Append(plainTextPassword);
    StringBuilder.Clear();
    // overwrite with reasonably random characters
    StringBuilder.Append(New Guid().ToString());
    
    推荐文章