OneSneakyMofo
OneSneakyMofo

Reputation: 1289

Weird characters using Encryption

in my program, I am encrypting and decrypting a .PNG file using the Triple DES algorithm. It encrypts and decrypts, but some of the characters in the .PNG are replaced with these characters: �

I figure it is a Unicode error, but I dunno what's up. Here's the code:

        byte[] encrypted_data = UTF8Encoding.UTF8.GetBytes(file_data);
        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = key;
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;
        ICryptoTransform cTransform = tdes.CreateEncryptor();
        byte[] resultArray =
        cTransform.TransformFinalBlock(encrypted_data, 0, encrypted_data.Length);
        tdes.Clear();
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);

Upvotes: 0

Views: 436

Answers (1)

Guffa
Guffa

Reputation: 700322

Yes, it's a unicode error. You have involved the encoding where it doesn't belong by reading the data as a string, so the error is before the code that you have shown.

You should read the data as binary data so that you get it as a byte array from the start, so that you can skip the conversion into unicode and back as that is what causes the error.

Upvotes: 1

Related Questions