Decrypt XML file error: Padding is invalid and cannot be removed

You can post your problem related to Microsoft Visual Studio Projects here. We will try our best to help you out.
Post Reply
Johnson
Posts: 18
Joined: Sat Feb 18, 2017 9:10 am

Decrypt XML file error: Padding is invalid and cannot be removed

Post by Johnson » Tue Mar 07, 2017 8:52 am

I encrypt an XML file and save it to the original file.
I then open the file and try to decrypt it, and get the error "Padding is invalid and cannot be removed".
I think this is because during encryption, I execute

Code: Select all

key = New RijndaelManaged()
And, during decryption, I also execute

Code: Select all

key = New RijndaelManaged()
How can I save the key from the encryption ?
Thank you.

This is the code to encrypt and save the XML file:

Code: Select all

Imports System.Xml
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml

Dim key As RijndaelManaged = Nothing
' Create a new Rijndael key.
key = New RijndaelManaged()
' Load an XML document.
Dim xmlDoc As New XmlDocument()
xmlDoc.PreserveWhitespace = True
xmlDoc.Load("myXMLFile.XML")
Encrypt(xmlDoc, "myElement1", key)
Encrypt(xmlDoc, "myElement2", key)
xmlDoc.Save("myXMLFile.XML")
This is the code to decrypt the XML file:

Code: Select all

Imports System.Xml
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml

Dim key As RijndaelManaged = Nothing
key = New RijndaelManaged()
Dim xmlDoc As New XmlDocument()
xmlDoc.PreserveWhitespace = True
xmlDoc.Load("myXMLFile.XML")
Decrypt(xmlDoc, key)

Post Reply