1

我在 C++ 中有一个加密例程,我将它翻译成 C#:

例子:

public void main()
{
    string myPwd = "ÖFÖæ6";
    string pwdCoded = XEncrypt.EncryptData_Patch_x_Net(myPwd);
    //Result OK: ÖFÖæ–6
}

public static string EncryptData_Patch_x_Net(string Data)
{
    byte[] bytes = new byte[Data.Length];

    for (int n = 0; n < Data.Length; n++)
    {
        bytes[n] = (byte)Data[n];
    }

    System.Text.Encoding MyEncoding = System.Text.Encoding.Default;
    String MyResult = MyEncoding.GetString(bytes);
    return MyResult;
}

我需要制作使其转换为的逆例程:

ÖFÖæ–6to ÖFÖæ6(注意左边的字符串中有一个破折号)

我做了最后一个功能,但错误地执行了编码

public static string DecryptData_Patch_x_Net(string Data)
{
    byte[] bytes = new byte[Data.Length];

    for (int n = 0; n < Data.Length; n++)
    {
        bytes[n] = (byte)Data[n];
    }

    System.Text.Encoding MyEncoding = System.Text.Encoding.GetEncoding(1252);
    String MyResult = MyEncoding.GetString(bytes);
    return MyResult;
}
4

2 回答 2

5

这不是加密,您正在严重复杂化它的实际情况。

Encoding iso88591 = Encoding.GetEncoding(28591);
Encoding w1252 = Encoding.GetEncoding(1252);

//
string pwd = "ÖFÖæ\u00966"; //The SPA control character will not survice a Stackoverflow post
                            //So I use \u0096 to represent it

string result = w1252.GetString(iso88591.GetBytes(pwd)); //"ÖFÖæ–6"

string original = iso88591.GetString(w1252.GetBytes(result)); //"ÖFÖæ6" with the hidden control character before 6

Console.WriteLine(result == "ÖFÖæ–6"); //True
Console.WriteLine(original == "ÖFÖæ\u00966"); //True
于 2013-01-09T14:50:12.833 回答
1

Your misnamed ...Encrypt... function makes a fundamental error. You take a string, which treat as a char[] (thats fine), then explicitly cast each char to a byte. That is a narrowing conversion. You'll lose any of the high bits and the ability to round trip more unusual chars. If you look at this question it should help to understand.

You could use this function to get the bytes without loss of information,

static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

The byte array will round trip on systems that share endianess.


As Esailija states, becuase its simple and it will explicitly return little endian results, you're better off calling

byte[] Encoding.Unicode.GetBytes(string)

To achieve the same.

于 2013-01-09T15:13:06.870 回答