0

I need help with string merging in vb.net. Is it possible to concatenate 2 secure strings together?

I have part1.securestring and part2.securesting and I want my output to be mainPassword = part1 + part2.

But it does not work. Do you have any ideas how to solve this? Thank you for your help.

Tadumc421
  • 149
  • 2
  • 4
  • 12
  • Hi. Welcome to stackoverflow, please read [ask] and provide [mcve] of your code and explain in detail ***what is not working***. "Does not work" does not tell us what do you expect to happen and what is actually happening. – Esko Jun 19 '18 at 07:17

2 Answers2

0

It would be easy to do if you converted the SecureStrings to Strings first, but that defeats the very purpose of SecureString, which is to not leave the sensitive information as a hanging string object in memory. You have to be careful to only work with byte arrays, and to zero-clear them afterwards.

<Extension()> _
Public Function Append(ByVal s1 As SecureString, ByVal s2 As SecureString) As SecureString
    Dim b() As Byte

    Dim p1 = Marshal.SecureStringToGlobalAllocUnicode(s1)
    Try
        Dim p2 = Marshal.SecureStringToGlobalAllocUnicode(s2)
        Try
            ReDim b(0 To s1.Length * 2 + s2.Length * 2 - 1)

            Marshal.Copy(p1, b, 0, s1.Length * 2)
            Marshal.Copy(p2, b, s1.Length * 2, s2.Length * 2)
        Finally
            Marshal.ZeroFreeGlobalAllocUnicode(p2)
        End Try
    Finally
        Marshal.ZeroFreeGlobalAllocUnicode(p1)
    End Try


    Dim res = New SecureString()
    For i As Integer = LBound(b) To UBound(b) Step 2
        res.AppendChar(BitConverter.ToChar(b, i))
    Next
    res.MakeReadOnly()
    Array.Clear(b, 0, b.Length)

    Return res
End Function

Usage:

Dim result = SecureString1.Append(SecureString2)
GSerg
  • 76,472
  • 17
  • 159
  • 346
-1

TO close. I found the solution:

Dim stringPart1 As String
Dim stringPart2 As String
Dim stringPart3 As String

stringPart1  = New System.Net.NetworkCredential(String.Empty,part1).Password
stringPart2 = New System.Net.NetworkCredential(String.Empty,part2).Password
stringPart3 = New System.Net.NetworkCredential(String.Empty,part3).Password


hasloGlowne = New Security.SecureString()

 For Each c As Char In stringpart1
        hasloGlowne.AppendChar(c)   
 Next    

  For Each c As Char In stringpart2
        hasloGlowne.AppendChar(c)   
 Next    

  For Each c As Char In stringpart3
        hasloGlowne.AppendChar(c)   
 Next   
  • You are decrypting the string and storing it in memory as plain text. This defeats the purpose of `SecureString`. These `stringPart1` etc are going to stay in memory after you're done with them. – GSerg Jun 19 '18 at 07:44