填充无效,无法使用Rijndael解密删除

时间:2013-01-11 14:28:36

标签: encryption rijndael

当我调用下面的方法从Windows应用程序解密字符串时,我看到“填充无效且无法删除”错误。字符串是从asp.net应用程序加密的。两个应用程序引用相同的程序集我能够加密和解密来自asp.net应用程序的任何问题。这是我进行加密和解密的主要代码。

    private static byte[] EncryptHelper(byte[] arrData, string Password, bool Encrypt)
    {
        //Create the SymetricAlgorithem object
        SymmetricAlgorithm myAlg = new RijndaelManaged();

        //define a salt value to derive the key.
        byte[] salt = System.Text.Encoding.ASCII.GetBytes("hjkhj877ffasah");

        //Instantiate Rfc2898DeriveBytes with the password and salt.
        Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(Password, salt);


        myAlg.Key = key.GetBytes(myAlg.KeySize / 8); 
        myAlg.IV = key.GetBytes(myAlg.BlockSize / 8); 
        myAlg.Padding = PaddingMode.PKCS7;
        //Create the ICryptoTransform Object
        ICryptoTransform encrytptor = Encrypt ? myAlg.CreateEncryptor() : myAlg.CreateDecryptor();

        //Create Memorystream to write the encrypted data
        using (MemoryStream aStream = new MemoryStream())
        {

            //Create the CryptoStream Ojbect using the aStream object
            using (CryptoStream encryptStream = new CryptoStream(aStream, encrytptor, CryptoStreamMode.Write))
            {
                //Write the contents to crypto stream
                encryptStream.Write(arrData, 0, arrData.Length);

                //Flush the cryptostream
                encryptStream.FlushFinalBlock();

                //Reposition the memorystream to write the contents to an array.
                aStream.Position = 0;

            }
            aStream.Flush();
            //Convert to an array and return
            return aStream.ToArray();

        }
    }

这是我用来将纯文本从/转换为字节数组

的方法
    private static byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }

    private static string GetString(byte[] bytes)
    {
        char[] chars = new char[bytes.Length / sizeof(char)];
        System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
        return new string(chars);
    }

为了将密文保存到数据库,我使用Convert.ToBase64String()和Convert.FromBase64String。问题出在我使用Rfc2898DeriveBytes类的方式吗?

1 个答案:

答案 0 :(得分:2)

嗯,我认为重要的是要提到从安全角度来看,对于每个具有相同密码的邮件,您将拥有相同的IV,并且可预测的IV实际上是 big no no

在那之后我有点不想再看看它出了什么问题,在stackoverflow上有很多非常糟糕的剪切和粘贴C#加密,他们只是坐在那里没有更新机制,没有一个人再次看着他们,除了人们发现他们再次剪切和粘贴。

请看Modern Examples of Symmetric Authenticated Encryption of a string. c#

我尽量保持最新并进行审核。