0

我正在尝试在 C# 中编写 xor 加密,因为 sagepay 加密仅记录在 VB 中。

VB代码是:

Public Shared Function simpleXor(ByVal strIn As String, ByVal strKey As String) As String
    Dim iInIndex As Integer
    Dim iKeyIndex As Integer
    Dim strReturn As String
    If Len(strIn) = 0 Or Len(strKey) = 0 Then
        simpleXor = ""
        Exit Function
    End If

    iInIndex = 1
    iKeyIndex = 1
    strReturn = ""

    '** Step through the plain text source XORing the character at each point with the next character in the key **
    '** Loop through the key characters as necessary **
    Do While iInIndex <= Len(strIn)
        strReturn = strReturn & Chr(Asc(Mid(strIn, iInIndex, 1)) Xor Asc(Mid(strKey, iKeyIndex, 1)))
        iInIndex = iInIndex + 1
        If iKeyIndex = Len(strKey) Then iKeyIndex = 0
        iKeyIndex = iKeyIndex + 1
    Loop

    simpleXor = strReturn
End Function

到目前为止,我已将其转换为

        public static String SimpleXOR(String strIn, String strKey)
    {
        Int32 iInIndex, iKeyIndex;
        String strReturn;
        iInIndex = 1;
        iKeyIndex = 1;
        strReturn = "";

        while (iInIndex <= strIn.Length)
        {
            strReturn = strReturn & Strings.Chr(Strings.Asc(Strings.Mid(strIn, iInIndex, 1)) ^ Strings.Asc(Strings.Mid(strKey, iKeyIndex, 1)));
                iInIndex = iInIndex + 1;
            if (iKeyIndex == strKey.Length) iKeyIndex = 0;
            iKeyIndex = iKeyIndex + 1;

        }

    }

问题是我不明白这条线在做什么

strReturn = strReturn & Chr(Asc(Mid(strIn, iInIndex, 1)) Xor Asc(Mid(strKey, iKeyIndex, 1)))

所以我通过一个 vb 到 c# 转换器运行它并得到了上述内容。但据我所知,它显然不是有效的 c# 代码。

任何人都可以帮忙吗?

4

2 回答 2

2

我可以想到两种方法来做到这一点:

首先,获取线程的当前 System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage,使用 GetEncoding 方法将其传递给新的 Encoding 类实例,然后使用 Encoding 实例的 GetBytes 方法将字符串转换为字节数组

    public static string SimpleXOR(string strIn, string strKey)
    {
        if (strIn.Length == 0 || strKey.Length == 0)
        {
            return string.Empty;
        }

        int inIndex = 0;
        int keyIndex = 0;
        string returnString = string.Empty;

        var currentCodePage = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage;
        var encoding = Encoding.GetEncoding(currentCodePage);

        var inString = encoding.GetBytes(strIn);
        var keyString = encoding.GetBytes(strKey);

        while (inIndex < inString.Length)
        {
            returnString += (char)(inString[inIndex] ^ keyString[keyIndex]);

            inIndex++;

            if (keyIndex == keyString.Length - 1)
            {
                keyIndex = 0;
            }
            else
            {
                keyIndex++;
            }
        }

        return returnString;
    }

另一种更简单的方法是在 C# 项目中添加对 Microsoft.VisualBasic 的引用,并让转换器生成的代码运行。Strings 类将可用,允许您只执行 Strings.Chr、Strings.Asc 和 Strings.Mid。

于 2012-12-03T17:40:24.300 回答
0

在 C# 中,这只是

strReturn += (char)(strIn[iInIndex] ^strKey[iKeyIndex]);
于 2012-12-03T16:05:57.613 回答