[RESOLVED] [2005] Recognizing null from byte string
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
Re: [2005] Recognizing null from byte string
ok, I found a better way to get rid of it;
s = s.Replace(vbNullChar, "")
or
If s.Substring(s.Length - 1, 1) = Chr(0) Then s = s.Replace(vbNullChar, "")
(but I still dont understand why it's there).
Re: [2005] Recognizing null from byte string
The reason it's there is because BSTR is a null terminated string.
Re: [2005] Recognizing null from byte string
Are you trying to basically just make it to a STring? If so, you could replace the codes
VB Code:
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
and just use
VB Code:
Dim mystr As String = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(bstr)
By the way, are you using SecureString for the purpose of security? Based on what I read, SecureString's purpose is to avoid having to store certain data on a string variable, but since you convert the securestring to a string, doesn't that take way its purpose? Just curious.
Re: [2005] Recognizing null from byte string
ok, thanks.
Agreed on the security issue. I need to store a key in the executable, so a secure string is the only option. I wrote a converter the other way around to check the string was actually being stored correctly. I wont be using the back converter in practice, I can use hashes to compare.
Secure strings are a bit of joke actually, since they are currently poorly supported by controls/methods. In most applications a secure string has to be briefly pulled back as a string in order to use its value, which of course exposes it on the heap. I think there are improvements on the way.