Rijndael encoding based on 64 in C#

Asked

Viewed 426 times

1

I’m doing a Rijndael encryption and I imagine I’m close to finishing it, but when I decrypt I’m in 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 executing 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 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 in advance if anyone can give me a light, on why this error is occurring, I am running on console application in case only for testing.

1 answer

0


Either your encoding or the decryption is not right. You have to understand that to decrypt a cipher Rijndael Voce needs the same IV and the same key. Therefore Voce cannot encrypt the IV along with the message.

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

I will put your code working here, it will not be very different from the example of msdn.

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 Voce you can implement a ToString in class EnciptedData

public override string ToString(){
    return Convert.ToBase64String(IV) + "&" + Convert.ToBase64String(Data);
}
  • I did the tests and adjusted here to the point I need to encrypt, also beating with encryption done there in PHP and I got, thank you very much for the help, from heart.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.