public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s) { if (s == null) throw new ArgumentNullException ("s"); int len = s.Length; IntPtr ctm = AllocCoTaskMem (len + 1); byte [] copy = new byte [len+1]; try { byte [] buffer = s.GetBuffer (); int i = 0, j = 0; for (; i < len; i++, j += 2){ copy [i] = buffer [j+1]; buffer [j] = 0; buffer [j+1] = 0; } copy [i] = 0; copy_to_unmanaged (copy, 0, ctm, len+1); } finally { // Ensure that we clear the buffer. for (int i = len; i > 0; ){ i--; copy [i] = 0; } } return ctm; }
public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s) { if (s == null) throw new ArgumentNullException ("s"); int len = s.Length; IntPtr ctm = AllocCoTaskMem (len * 2 + 2); byte [] buffer = null; try { buffer = s.GetBuffer (); for (int i = 0; i < len; i++) WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1]))); WriteInt16 (ctm, buffer.Length, 0); } finally { if (buffer != null) for (int i = buffer.Length; i > 0; ){ i--; buffer [i] = 0; } } return ctm; }
public static IntPtr SecureStringToBSTR (SecureString s) { if (s == null) throw new ArgumentNullException ("s"); int len = s.Length; IntPtr ctm = AllocCoTaskMem ((len+1) * 2 + 4); byte [] buffer = null; WriteInt32 (ctm, 0, len*2); try { buffer = s.GetBuffer (); for (int i = 0; i < len; i++) WriteInt16 (ctm, 4 + (i * 2), (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1]))); WriteInt16 (ctm, 4 + buffer.Length, 0); } finally { if (buffer != null) for (int i = buffer.Length; i > 0; ){ i--; buffer [i] = 0; } } return (IntPtr) ((long)ctm + 4); }