简体   繁体   English

AES-128-ECB解密:输入数据不是完整的块

[英]AES-128-ECB decryption: The input data is not a complete block

I am trying to write a code which would decrypt a text which was encrypted with AES-128-ECB and represented in Base64. 我正在尝试编写代码来解密用AES-128-ECB加密并以Base64表示的文本。 The key is known (it's a task for educational purposes) and presented in ASCII (for example, YELLOW SUBMARINE). 密钥是已知的(出于教育目的,这是一项任务),并以ASCII(例如,YELLOW SUBMARINE)表示。

Here is the code: 这是代码:

    private void button6_Click(object sender, EventArgs e)
    {
        string CTChar = Funcs.BitsToChar(Funcs.B64ToBits(textBox1.Text));
        Byte[] CTBytes = new Byte[CTChar.Length];
        for (int iCounter = 0; iCounter < CTChar.Length; iCounter++)
        {
            CTBytes[iCounter] = Convert.ToByte(CTChar[iCounter]%256);
        }
        string KeyBits = Funcs.CharToBits(textBox2.Text);
        Byte[] KeyBytes = new Byte[textBox2.TextLength];
        string PlainText = null;
        Aes Decryptor = Aes.Create();
        Decryptor.BlockSize = 128;
        for (int iCounter = 0; iCounter < textBox2.Text.Length; iCounter++)
        {
            KeyBytes[iCounter] = Convert.ToByte(textBox2.Text[iCounter]);
        }
        Decryptor.KeySize = textBox2.TextLength * 8;
        Decryptor.Key = KeyBytes;
        Decryptor.Mode = CipherMode.ECB;
        ICryptoTransform Decr = Decryptor.CreateDecryptor();

        using (MemoryStream msDecrypt = new MemoryStream(CTBytes))
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, Decr, CryptoStreamMode.Read))
            {
                using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                {
                    PlainText = srDecrypt.ReadToEnd();
                }
            }
        }
        textBox3.Text = PlainText;
    }

When running it and trying to decrypt a text, an error occurs: The input data is not a complete block (Cryptographic Exception was unhandled). 运行它并尝试解密文本时,会发生错误:输入数据不是完整的块(未处理Cryptographic Exception)。 What am I doing wrong? 我究竟做错了什么?

You should convert base 64 - which seems to be the format of the input ciphertext - directly to a Byte[]. 您应该将base 64(似乎是输入密文的格式)直接转换为Byte []。 You are currently converting it to bits, then to characters, then to bytes. 您当前正在将其转换为位,然后转换为字符,然后转换为字节。 Base 64 has been defined to encode bytes (or octets) to text. 基数64已定义为将字节(或八位字节)编码为文本。

Converting bytes with a random value to/from text will get you in trouble; 将带有随机值的字节转换为文本或从文本转换会给您带来麻烦; it is one of the reasons why base 64 exists in the first place. 这是为什么首先存在base 64的原因之一。 Try and find a correct base 64 implementation for your platform, there should be plenty, even in the standard API. 尝试为您的平台找到正确的base 64实现,即使在标准API中也应该有很多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM