变量防止更多文本附加到字符串?

时间:2014-08-04 16:05:45

标签: vb.net cryptography rijndaelmanaged stringwriter

我现在迷失了为什么我不能得到这么简单的工作!

我正在解密一个值&将其附加到字符串,例如

 MessageBox.Show("TEST 1: " & DecryptedValue & " WHY AM I BEING STRIPPED???")

问题是,在从字符串中删除DecryptedValue之后的任何内容。

下面的完整项目/表单示例显示了此问题:

Imports System.Text
Imports System.Security.Cryptography
Imports System.IO

Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim DecryptedValue As String = Decrypt("mDnz8JVmfUyYxkgZYYiFbw==", "IXZOfRxCtb4pQcu2")
        MessageBox.Show("TEST 1: " & DecryptedValue & " WHY AM I BEING STRIPPED???")

        Dim sw As New StringWriter
        sw.Write("TEST 2 ")
        sw.Write(DecryptedValue)
        sw.Write("WHY AM I BEING STRIPPED???")
        MessageBox.Show(sw.ToString())

        Dim okstr As String = "Ok"
        MessageBox.Show("When Anything " & "Else " & "Works " & okstr)
    End Sub

    Friend Function Decrypt(ByVal str As String, ByVal key As String) As String
        Dim cipher As Byte() = Convert.FromBase64String(str)
        Dim btKey As Byte() = Encoding.ASCII.GetBytes(key)
        Dim decryptor As ICryptoTransform = New RijndaelManaged() With { _
            .Mode = CipherMode.ECB, _
            .Padding = PaddingMode.None _
        }.CreateDecryptor(btKey, Nothing)
        Dim ms As New MemoryStream(cipher)
        Dim cs As New CryptoStream(ms, decryptor, CryptoStreamMode.Read)
        Dim plain As Byte() = New Byte(cipher.Length - 1) {}
        Dim count As Integer = cs.Read(plain, 0, plain.Length)
        ms.Close()
        cs.Close()
        Return Encoding.UTF8.GetString(plain, 0, count)
    End Function

End Class

过去是否有人遇到过这个问题/能否发现我正在寻找的基本内容?

1 个答案:

答案 0 :(得分:1)

如果解密的返回包含Null(Chr(0)),则不会“看到”附加的文本。这是因为Chr(0)/ Null是字符串终止字符。

Dim sb As New StringBuilder

sb.Append("first part of string" & Convert.ToChar(0))
sb.Append("this is added")

Console.WriteLine(sb.ToString)
Console.WriteLine(sb.ToString.Length)

仅显示第一部分,但长度将报告34,其中还包括嵌入的Null。创建的字符串实际上是34个字符长,但大多数都停在Chr(0)。

控制台甚至看不到在整个字符串后发送的换行符,因此显示为:

first part of string34

有关其工作方式/原因的详细信息,请参阅this answer