填充無效,無法刪除?我已經(jīng)在線查看了這個異常對我的程序的意義,但似乎無法找到解決方案或者為什么它會發(fā)生在我的特定程序中。我一直在使用我的msdn提供的示例,用于使用Rijndael算法加密和解密XmlDocument。加密工作正常,但是當我嘗試解密時,我得到以下異常:填充無效,無法刪除誰能告訴我我能做些什么來解決這個問題?我的代碼是我獲取密鑰和其他數(shù)據(jù)的地方。如果cryptoMode為false,它將調用decrypt方法,這是異常發(fā)生的地方: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 回答

慕虎7371278
TA貢獻1802條經(jīng)驗 獲得超4個贊
請確保您使用的密鑰進行加密和解密是相同的。填充方法即使沒有明確設置,仍應允許正確的解密/加密(如果沒有設置它們將是相同的)。但是,如果由于某種原因使用不同的密鑰集進行解密而不是用于加密,則會出現(xiàn)此錯誤:
填充無效,無法刪除
如果您使用某種算法來動態(tài)生成無效的密鑰。加密和解密都需要相同。一種常見的方法是讓調用者在加密方法類的構造函數(shù)中提供密鑰,以防止加密/解密過程有任何創(chuàng)建這些項的過程。它側重于手頭的任務(加密和解密數(shù)據(jù)),并要求調用者提供iv
和key
提供。

眼眸繁星
TA貢獻1873條經(jīng)驗 獲得超9個贊
為了人們搜索的好處,可能值得檢查被解密的輸入。在我的情況下,發(fā)送用于解密的信息(錯誤地)作為空字符串進入。它導致填充錯誤。
這可能與rossum的答案有關,但認為值得一提。
- 3 回答
- 0 關注
- 630 瀏覽
添加回答
舉報
0/150
提交
取消