How to convert SecureString to System.String?

后端 未结 11 838
孤独总比滥情好
孤独总比滥情好 2020-11-27 10:22

All reservations about unsecuring your SecureString by creating a System.String out of it aside, how can it be done?

How can I convert an ordinary S

11条回答
  •  醉话见心
    2020-11-27 10:55

    Use the System.Runtime.InteropServices.Marshal class:

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

    If you want to avoid creating a managed string object, you can access the raw data using 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);
      }
    }
    

提交回复
热议问题