user1961529
user1961529

Reputation: 11

C# Encoding Conversion

I have an encrypt routine in c++, I translate this to C#:

example:

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;
}

I need to make the inverse routine that made it convert from:

ÖFÖæ–6 to ÖFÖæ6 (notice there's a dash in the left string)

I did this last function, but erroneously performs the encoding

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;
}

Upvotes: 1

Views: 1749

Answers (2)

Jodrell
Jodrell

Reputation: 35746

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.

Upvotes: 1

Esailija
Esailija

Reputation: 140234

This is not encryption and you are seriously complicating what it actually is.

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

Upvotes: 5

Related Questions