VB.net Base64 + XOR

时间:2017-10-07 14:26:46

标签: vb.net encryption base64 xor

所以我想创建一个可以加密和解密到Base64的函数,然后用密钥对它进行异或。

到目前为止,这是我的代码:

    Imports System.Text

   Module Module1

    Private key As String = "37526"


    Sub Main()
        Dim test As String = Console.ReadLine
        test = Decrypt(test)
        Console.WriteLine(test)
        Main()

    End Sub

    Public Function Decrypt(CipherText As String) As String

        Dim decoded = Convert.FromBase64String(CipherText)
        Dim dexored = [xor](decoded, key)
        Return Encoding.UTF8.GetString(dexored)

    End Function

    Private Function [xor](text As Byte(), key As String) As Byte()
        Dim res As Byte() = New Byte(text.Length - 1) {}
        For c As Integer = 0 To text.Length - 1
            res(c) = CByte((text(c)) Xor CUInt(Val(c Mod key.Length)))
        Next

        Return res
    End Function


    Public Function Encrypt(Plaintext As String)

        Dim encoded = Encoding.UTF8.GetBytes(Plaintext)
        Dim xored = [xor](encoded, key)
        Return Convert.ToBase64String(xored)

    End Function

End Module

所以这就是我的问题:这段代码工作正常,但是我试图解密这个字符串" X1hZXVoCBQY =",该字符串的解密应该是" lolol123&#34 ;.我不知道我的代码是错还是密钥错误。有人可以检查我的代码或给我正确的密钥吗?我试图强行使用钥匙,但这对我来说很有用。如果我尝试解密字符串,我就不会得到" lolol123",我得到" _Y [^^"

1 个答案:

答案 0 :(得分:0)

xor功能出错了。试图在一行中做太多可能会让它太复杂而无法立即看到发生了什么,所以我开始重新编写它,就像我将要做的那样,并且在我开始查看任何内容之前快速检查它是否正常工作否则:

Option Infer On
Option Strict On
' ...
Private Function [xor](text As Byte(), key As String) As Byte()
    Dim res As Byte() = New Byte(text.Length - 1) {}
    Dim keyBytes = Encoding.UTF8.GetBytes(key)

    For c = 0 To text.Length - 1
        res(c) = CByte((text(c)) Xor keyBytes(c Mod keyBytes.Length))
    Next

    Return res

End Function