Ho cercato online cosa significhi questa eccezione in relazione al mio programma ma non riesco a trovare una soluzione o il motivo per cui sta accadendo al mio programma specifico. Ho utilizzato l'esempio fornito il mio msdn per crittografare e decifrare un XmlDocument usando l'algoritmo Rijndael. La crittografia funziona bene, ma quando provo a decifrare, ottengo la seguente eccezione:Il riempimento non è valido e non può essere rimosso?
Padding is invalid and cannot be removed
Qualcuno può dirmi cosa posso fare per risolvere questo problema? Il mio codice qui sotto è dove ottengo la chiave e altri dati. Se il cryptoMode è falso, chiamerà il metodo decrypt, che è dove si verifica l'eccezione:
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);
}
Puoi fare un tentativo impostando esplicitamente la modalità di riempimento in modo identico sia per la crittografia sia per la decifratura per essere indentici. Ad esempio: alg.Padding = PaddingMode.NONE; – NetSquirrel
Che aspetto ha il metodo Encrypt()? –
Grazie ragazzi che hanno funzionato. –