Search code examples
c#encryptiondiacriticsrijndael

Rijandeal and special characters


I'm using Rijandeal for enc./dec. and I noticed that some special characters are not correctly managed.

Here is the code:

    static void Main(string[] args)
    {        
        string enc = RijanENC("šđčćž");
        string dec = RijanDEC(enc);

        Console.WriteLine(dec);
        Console.ReadKey();
    }

    private static string RijanENC(string texto_puro)
    {
        byte[] key = System.Text.Encoding.Default.GetBytes("123abc12");
        byte[] iv = System.Text.Encoding.Default.GetBytes("0123456789abcdef");
        byte[] stringToEncrypt = System.Text.Encoding.UTF32.GetBytes(texto_puro);


        Rijndael rjnAlg = Rijndael.Create();
        System.IO.MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, rjnAlg.CreateEncryptor(key, iv), CryptoStreamMode.Write);
        cs.Write(stringToEncrypt, 0, stringToEncrypt.Length);
        cs.FlushFinalBlock();
        return Convert.ToBase64String(ms.ToArray());
    }

    private static string RijanDEC(string texto_encriptado)
    {
        byte[] key = System.Text.Encoding.Default.GetBytes("123abc12");
        byte[] iv = System.Text.Encoding.Default.GetBytes("0123456789abcdef");
        byte[] stringToDecrypt = new byte[texto_encriptado.Length];


        Rijndael rjnAlg = Rijndael.Create();
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, rjnAlg.CreateDecryptor(key, iv), CryptoStreamMode.Write);
        stringToDecrypt = Convert.FromBase64String(texto_encriptado);
        cs.Write(stringToDecrypt, 0, stringToDecrypt.Length);
        cs.FlushFinalBlock();

        Encoding encoding = Encoding.UTF32;
        return encoding.GetString(ms.ToArray());
    }

So the text I want to enc. contains some diacritic characters šđčćž. After decoding i get sdccz instead even if using UTF32.


Solution

  • The code for encrypting/decrypting works as expected, the console output is the problem.

    Set the outputEncoding to display the characters in the proper encoding

    Console.OutputEncoding = System.Text.Encoding.UTF8;
    Console.WriteLine(dec);
    Console.ReadKey();