Rijndael encoding with base 64 in C #

1

I'm doing a Rijndael encryption and I imagine I'm close to finishing it, but when decrypting I get the error:

  

Invalid length of data to be decrypted.

using System.Text;

using static Array;

class EncoderRijndael
{

    public static Rijndael InstanciaRijndael()
    {


        Rijndael cripto = Rijndael.Create();

        cripto.KeySize = 128;
        cripto.Mode = CipherMode.CBC;
        cripto.Padding = PaddingMode.PKCS7;
        //cripto.GenerateKey(); //= Encoding.ASCII.GetBytes(key); //associação à propriedade Key
        cripto.GenerateIV();  //=  Encoding.ASCII.GetBytes(iv); //associação à propriedade do vetor de inicialização IV.
        cripto.Key = CriptoMD5.EncoderMD5.EncodeMD5(md5generate: "123");



        return cripto;
    }

    public static string Encripta(string plaintext)
    {
       using (Rijndael cripto = InstanciaRijndael()){ //instanciada a classe Rijndael
            ICryptoTransform encrypt = cripto.CreateEncryptor(cripto.Key, cripto.IV); //objeto encrypt para a execução das operações de transformação de criptografia.
            using (MemoryStream streamResultado = new MemoryStream()) //instancia a memória para armazenamento em memory stream.
          {
                using (CryptoStream cStream = new CryptoStream(streamResultado, encrypt, CryptoStreamMode.Write)) //instanciado a classe crypto stream para referenciar que a
                                                                                            //será feita fluxo Crypto Transform e memory stream
                {
                    using (StreamWriter writer = //instanciado o stream writer para indicar que será feito o processo de escrita de dados criptografados no objeto memory stream
                       new StreamWriter(cStream))
                    {
                        writer.Write(plaintext); //associando o texto em que será criptografado.
                    }
                }
              String concat = System.Text.Encoding.UTF8.GetString(cripto.IV);
              String auxMStream = System.Text.Encoding.UTF8.GetString(streamResultado.ToArray());
              String.Concat(concat, auxMStream);
              concat.Trim();
              var debyte64 = Encoding.UTF8.GetBytes(concat);
              concat = Convert.ToBase64String(debyte64);

              return concat;
          }
        }



    }

    public static string Decripta(string concat, string textdecrypted)

    {
        var concaat = Convert.FromBase64String(concat);
        concaat = Encoding.UTF8.GetBytes(concat);
        using (var cripto = InstanciaRijndael())
        {
            int btLength = concat.Length - 16;
            Debugger.Break();
            byte[] decryBT = new byte[btLength];

            Copy(concaat, 1, decryBT, 0, btLength);
            Debugger.Break();

            //System.Text.Encoding.UTF8.GetBytes(newIV);
            byte[] newIV = new byte[16];
            Copy(concaat, newIV, 16);

            cripto.IV = newIV;                
            var decrypt = cripto.CreateDecryptor(cripto.Key, cripto.IV);

            using (var streamCryptText = new MemoryStream(decryBT))
            {
                using (var cStream = new CryptoStream(streamCryptText, decrypt, CryptoStreamMode.Read))

                {

                    using (var reader = new StreamReader(cStream))
                    {
                      textdecrypted = reader.ReadLine();
                        Debugger.Break();
                    }
                }
            }
        }
        return textdecrypted;
    } 
}
}

Main method for running it.

class Executa
{
    class Program
    {
        public static void Main(string[] args)
        {
            var keyRij = CriptoRijndael.EncoderRijndael.Encripta(plaintext: "teste cripto");
            String textdecrypted = "";
            CriptoRijndael.EncoderRijndael.Decripta(concat: keyRij, textdecrypted: textdecrypted);

            Console.WriteLine(textdecrypted);
            Console.ReadLine();
        }
    }
}
}

Code for generating the MD5 Hash key being used key "123"

class EncoderMD5
{


public static byte[] EncodeMD5(String md5generate)
    {
        MD5 md5Hash = MD5.Create();
        byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(md5generate)); // converte para array de bytes
        StringBuilder sb = new StringBuilder();            
        foreach (byte t in data) //formatar byte para string decimal
        {
            sb.Append(t.ToString("x2"));
        }
        var key = Encoding.ASCII.GetBytes(sb.ToString());

        return key;
    }
}
}

Thanks, if anyone can give me a light on why this error is occurring, I'm running in console application in case just for testing.

    
asked by anonymous 06.07.2017 / 22:03

1 answer

0

Whether your coding or decoding is not right. You have to understand that to decrypt a% cipher of% you need the same IV and the same key. So you can not encrypt the IV together with the message.

You can see exactly what in the example MSDN they use the same IV. You should have seen this example since your code is not much different.

I'm going to put your code here, it will not be very different from the msdn example.

class EncoderRijndael
{

    public static byte[] EncodeMD5(String md5generate)
    {
        MD5 md5Hash = MD5.Create();
        byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(md5generate)); // converte para array de bytes
        StringBuilder sb = new StringBuilder();            
        foreach (byte t in data) //formatar byte para string decimal
        {
            sb.Append(t.ToString("x2"));
        }
        var key = Encoding.ASCII.GetBytes(sb.ToString());

        return key;
    }

    public static Rijndael InstanciaRijndael()
    {
        Rijndael cripto = Rijndael.Create();

        cripto.KeySize = 128;
        cripto.Mode = CipherMode.CBC;
        cripto.Padding = PaddingMode.PKCS7;
        cripto.GenerateIV();
        cripto.Key = EncodeMD5(md5generate: "123");



        return cripto;
    }

    public class EnciptedData{
        public byte[] IV{get; set;}
        public byte[] Data{get; set;}
    }

    public static EnciptedData Encripta(string plaintext)
    {
       using (Rijndael cripto = InstanciaRijndael()){ //instanciada a classe Rijndael
            ICryptoTransform encrypt = cripto.CreateEncryptor(cripto.Key, cripto.IV); //objeto encrypt para a execução das operações de transformação de criptografia.
            using (MemoryStream streamResultado = new MemoryStream()) //instancia a memória para armazenamento em memory stream.
          {
                using (CryptoStream cStream = new CryptoStream(streamResultado, encrypt, CryptoStreamMode.Write)) //instanciado a classe crypto stream para referenciar que a
                                                                                            //será feita fluxo Crypto Transform e memory stream
                {
                    using (StreamWriter writer = //instanciado o stream writer para indicar que será feito o processo de escrita de dados criptografados no objeto memory stream
                       new StreamWriter(cStream))
                    {
                        writer.Write(plaintext); //associando o texto em que será criptografado.
                    }
                }
                return new EnciptedData{
                    IV = cripto.IV,
                    Data = streamResultado.ToArray()
                };
          }
        }



    }

    public static string Decripta(EnciptedData data)
    {
        using (var cripto = InstanciaRijndael())
        {
            cripto.IV = data.IV;                
            var decrypt = cripto.CreateDecryptor(cripto.Key, cripto.IV);

            using (var streamCryptText = new MemoryStream(data.Data))
            {
                using (var cStream = new CryptoStream(streamCryptText, decrypt, CryptoStreamMode.Read))
                {
                    using (var reader = new StreamReader(cStream))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
        }
    } 
}

void Main(){
    var keyRij = EncoderRijndael.Encripta(plaintext: "teste cripto");
    EncoderRijndael.Decripta(keyRij);
}

Now if you want to view the encrypted data in base64 you can implement a Rijndael in class ToString

public override string ToString(){
    return Convert.ToBase64String(IV) + "&" + Convert.ToBase64String(Data);
}
    
07.07.2017 / 20:07