我已经在网上查找了此异常对我的程序的含义,但似乎找不到解决方案或它在我的特定程序中发生的原因。我一直在使用msdn提供的示例,使用Rijndael算法对XmlDocument进行加密和解密。加密工作正常,但是当我尝试解密时,出现以下异常:
填充无效,无法删除
谁能告诉我该如何解决这个问题?下面的代码是我获取密钥和其他数据的地方。如果cryptoMode为false,它将调用解密方法,这是发生异常的地方:
public void Cryptography(XmlDocument doc, bool cryptographyMode) { RijndaelManaged key = null; try { // Create a new Rijndael key. key = new RijndaelManaged(); const string passwordBytes = "Password1234"; //password here byte[] saltBytes = Encoding.UTF8.GetBytes("SaltBytes"); Rfc2898DeriveBytes p = new Rfc2898DeriveBytes(passwordBytes, saltBytes); // sizes are devided by 8 because [ 1 byte = 8 bits ] key.IV = p.GetBytes(key.BlockSize/8); key.Key = p.GetBytes(key.KeySize/8); if (cryptographyMode) { Ecrypt(doc, "Content", key); } else { Decrypt(doc, key); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { // Clear the key. if (key != null) { key.Clear(); } } } private void Decrypt(XmlDocument doc, SymmetricAlgorithm alg) { // Check the arguments. if (doc == null) throw new ArgumentNullException("Doc"); if (alg == null) throw new ArgumentNullException("alg"); // Find the EncryptedData element in the XmlDocument. XmlElement encryptedElement = doc.GetElementsByTagName("EncryptedData")[0] as XmlElement; // If the EncryptedData element was not found, throw an exception. if (encryptedElement == null) { throw new XmlException("The EncryptedData element was not found."); } // Create an EncryptedData object and populate it. EncryptedData edElement = new EncryptedData(); edElement.LoadXml(encryptedElement); // Create a new EncryptedXml object. EncryptedXml exml = new EncryptedXml(); // Decrypt the element using the symmetric key. byte[] rgbOutput = exml.DecryptData(edElement, alg); <---- I GET THE EXCEPTION HERE // Replace the encryptedData element with the plaintext XML element. exml.ReplaceData(encryptedElement, rgbOutput); }
Rijndael / AES是一个分组密码。它以128位(16个字符)的块加密数据。 加密填充用于确保消息的最后一块始终是正确的大小。
您的解密方法期望其默认填充是什么,并且找不到它。正如@NetSquirrel所说,您需要显式设置加密和解密的填充。除非您有其他理由,否则请使用PKCS#7填充。