为了账号安全,请及时绑定邮箱和手机立即绑定

填充无效,无法删除?

填充无效,无法删除?

C#
猛跑小猪 2019-08-12 18:35:52
填充无效,无法删除?我已经在线查看了这个异常对我的程序的意义,但似乎无法找到解决方案或者为什么它会发生在我的特定程序中。我一直在使用我的msdn提供的示例,用于使用Rijndael算法加密和解密XmlDocument。加密工作正常,但是当我尝试解密时,我得到以下异常:填充无效,无法删除谁能告诉我我能做些什么来解决这个问题?我的代码是我获取密钥和其他数据的地方。如果cryptoMode为false,它将调用decrypt方法,这是异常发生的地方: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();
查看完整描述

3 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

Rijndael / AES是一个块密码。它以128位(16个字符)块加密数据。 加密填充用于确保消息的最后一个块始终是正确的大小。

您的解密方法期望其默认填充是什么,并且没有找到它。正如@NetSquirrel所说,您需要为加密和解密显式设置填充。除非您有其他理由,否则请使用PKCS#7填充。


查看完整回答
反对 回复 2019-08-12
?
慕虎7371278

TA贡献1802条经验 获得超4个赞

请确保您使用的密钥进行加密解密相同的。填充方法即使没有明确设置,仍应允许正确的解密/加密(如果没有设置它们将是相同的)。但是,如果由于某种原因使用不同的密钥集进行解密而不是用于加密,则会出现此错误:

填充无效,无法删除

如果您使用某种算法来动态生成无效的密钥。加密和解密都需要相同。一种常见的方法是让调用者在加密方法类的构造函数中提供密钥,以防止加密/解密过程有任何创建这些项的过程。它侧重于手头的任务(加密和解密数据),并要求调用者提供ivkey提供。


查看完整回答
反对 回复 2019-08-12
?
眼眸繁星

TA贡献1873条经验 获得超9个赞

为了人们搜索的好处,可能值得检查被解密的输入。在我的情况下,发送用于解密的信息(错误地)作为空字符串进入。它导致填充错误。

这可能与rossum的答案有关,但认为值得一提。


查看完整回答
反对 回复 2019-08-12
  • 3 回答
  • 0 关注
  • 544 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信