I'm trying to convert a securestring to a string using the function below. However, the returned string always has one additional character appended which I think is a null. No matter what I do with "nothing", "vbnull", "dbnull" etc. this extra character is always present. I've even tried doing a .Replace on the final string but whatever it is remains.
The only fix I've found is to clip it off using a .Substring, but this is a nasty kludge.
Anyone see what I'm doing wrong?
VB Code:
Public Function SecureStringToString(ByVal str As System.Security.SecureString) As String Dim bstr As IntPtr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(str) Dim b As Byte = 1 Dim i As Integer = 0 Dim s As String = "" While Chr(b) <> Chr(0) 'I also tried IsNothing, IsNull, IsDBNull, = vbNull, = Nothing b = System.Runtime.InteropServices.Marshal.ReadByte(bstr, i) i += 2 s += Chr(b) End While s = s.Substring(0, s.Length - 1) 'This line is the kludge System.Runtime.InteropServices.Marshal.FreeBSTR(bstr) Return s End Function




Reply With Quote