Aes Encryption… missing an important piece

允我心安 提交于 2019-12-14 02:36:55

问题


I have a method in my static Encryption class that looks like this:

    public static byte[] EncryptString(string toEncrypt, byte[] encryptionKey)
    {
        var toEncryptBytes = Encoding.UTF8.GetBytes(toEncrypt);
        using (var provider = new AesCryptoServiceProvider())
        {
            provider.Key = encryptionKey;
            provider.Mode = CipherMode.ECB;
            provider.Padding = PaddingMode.ISO10126;
            using (var encryptor = provider.CreateEncryptor(provider.Key, provider.IV))
            {
                using (var ms = new MemoryStream())
                {
                    using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    {
                        cs.Write(toEncryptBytes, 0, toEncryptBytes.Length);
                        cs.FlushFinalBlock();
                    }
                    return ms.ToArray();
                }
            }
        }
    }

I have a unit test that looks like this:

    [TestMethod]
    public void EncryptStringEncryptsTest()
    {
        var toEncrypt = "My text to encrypt";
        var encryptionKey = Convert.FromBase64String("93mcgv9UBYpwgoUX0AXEaU1BqTCufPWPkFdOdoILLDA=");
        var encrypted = Encryption.EncryptString(toEncrypt, encryptionKey);

        var text = Convert.ToBase64String(encrypted);
        Assert.IsTrue(false);
    }

Every time I run this, the text value changes. I would expect it to be constant, given the same inputs. Am I wrong to expect that, or am I doing something wrong?


回答1:


Your assumption is incorrect.

ISO10126 padding will append random data to pad your message to a multiple of the block size.




回答2:


You are using random padding bytes, per ISO10126. So the results will not be the same each time, even with all inputs the same.



来源:https://stackoverflow.com/questions/8041153/aes-encryption-missing-an-important-piece

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!