繁体   English   中英

带有ECB密码模式的AES 128位是否使用无效密钥正确解密?

[英]AES 128 bit with ECB ciphermode algorithm decrypts correctly with an invalid key?

嗨,我正在学习加密/解密部分。 我使用带有ECB密码模式和PKCS7填充的AES 128位创建了两种加密/解密方法。

下面是代码。

public class EncClass
    {
        public string Encrypt(string text)
        {

            byte[] src = Encoding.UTF8.GetBytes(text);
            byte[] key = Encoding.ASCII.GetBytes("contactcentre");
            RijndaelManaged aes = new RijndaelManaged();
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;
            aes.KeySize = 128;

            using (ICryptoTransform encrypt = aes.CreateEncryptor(key, null))
            {
                byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
                encrypt.Dispose();
                return Convert.ToBase64String(dest);
            }
        }

        public string Decrypt(string text)
        {

            byte[] src = Convert.FromBase64String(text);
            RijndaelManaged aes = new RijndaelManaged();
            byte[] key = Encoding.ASCII.GetBytes("contactcentrT");
            aes.KeySize = 128;
            aes.Padding = PaddingMode.PKCS7;
            aes.Mode = CipherMode.ECB;
            using (ICryptoTransform decrypt = aes.CreateDecryptor(key, null))
            {
                byte[] dest = decrypt.TransformFinalBlock(src, 0, src.Length);
                decrypt.Dispose();
                return Encoding.UTF8.GetString(dest);
            }
        }
    }

请注意,在加密中,我已通过contactcentre密钥,在解密时,我已通过contactcentrT 在这种情况下,它正在进行适当的加密和解密。

    var encString = encClass.Encrypt(@"manoj");
    var decString = encClass.Decrypt(encString);

虽然我的两个键都不匹配,但它仍然正常工作。 只是想知道这会怎么样?

您将无效密钥传递给aes.CreateEncryptor (和CreateDecryptor )。 AES的有效密钥大小为128,192和256,密钥为13 * 8 = 104位。 如果您尝试将其分配给aes.Key - 这将抛出异常。 但是, aes.CreateEncryptor有一个错误,如果密钥大小小于块大小(小于128位),它无法正确验证密钥大小,尽管在文档中明确指出“密钥大小必须是128,192或256位”。 这个错误在.NET Core中修复(至少在版本2中),它正确地抛出了代码的异常。

因此,由于您错误地传递了无效密钥和CreateEncryptor ,因此您无法使用AES加密,任何事情都可能发生。 例如,如果传递1个字节(或2或7)的密钥 - 将抛出索引超出范围的异常。 我的假设(通过查看源代码)是算法实现假设密钥大小(以字节为单位)可以除以4,并使用这些4字节块。 键的前12个字符是相同的,其余的(不是1,2或3个字符)不使用,因为4字节块的数量计算为keySize / 4 (和keySize / 4 = 3)。

无论如何,对于为什么会发生这种情况的任何假设并不重要,因为算法是使用无效输入执行的,并且通过这样做产生的任何结果都是无关紧要的。

鉴于该信息 - 永远不会直接将密钥传递给aes.CreateEncryptor但首先将其分配给aes.Key然后传递( aes.CreateEncryptor(aes.Key, iv)

暂无
暂无

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

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