.net安全字符串连接

时间:2018-06-19 07:15:28

标签: vb.net string-concatenation securestring

我在vb.net中需要有关字符串合并的帮助。 是否可以将2个安全字符串连接在一起?

我有part1.securestring和part2.securesting,我希望我的输出是mainPassword = part1 + part2。

但它不起作用。 你有任何想法如何解决这个问题?谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

如果您首先将SecureString转换为String,那将会很容易,但是这会使SecureString的目的失败,即不将敏感信息保留为内存中挂着一个字符串对象。你必须小心只使用字节数组,然后将它们清零。

<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

用法:

Dim result = SecureString1.Append(SecureString2)

答案 1 :(得分:-1)

关闭。 我找到了解决方案:

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