I am encrypting my data before saving it into the XML file but I am being given the following error when trying to read (load()) from files :
System.Security.Cryptography.CryptographicException: 'Bad Data.'
The data is written (save()) correctly and is encypted.
The following is the save() method:
- protected static List Load(string typeName) where T:Person
- {
- byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8 };
-
- byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
-
-
-
-
-
-
-
- List result = new List();
-
- string targetDirectory = CreateTargetDirectory(typeName);
-
- string[] xmlFilePaths = Directory.GetFiles(targetDirectory, "*.xml");
-
-
- BinaryFormatter bformatter = new BinaryFormatter();
-
- DESCryptoServiceProvider des = new DESCryptoServiceProvider();
-
- foreach (string xmlFilePath in xmlFilePaths)
- {
-
-
- using (var fs = new FileStream(xmlFilePath, FileMode.Open, FileAccess.Read))
- using (var cryptoStream = new CryptoStream(fs, des.CreateDecryptor(key, iv), CryptoStreamMode.Read))
- {
- BinaryFormatter formatter = new BinaryFormatter();
-
- T person = (T)formatter.Deserialize(cryptoStream);
- result.Add(person);
- }
- }
-
- return result;
- }
The following is the save() method:
- protected void Save(string typeName)
- {
- string targetDirectory = CreateTargetDirectory(typeName);
- byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8 };
-
- byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
-
- string filePath = targetDirectory + ID + ".xml";
-
-
-
-
-
-
-
- BinaryFormatter bformatter = new BinaryFormatter();
- DESCryptoServiceProvider des = new DESCryptoServiceProvider();
-
-
-
-
-
-
-
-
- using (var fs= new FileStream(filePath, FileMode.Create, FileAccess.Write))
- using (var cryptoStream = new CryptoStream(fs, des.CreateEncryptor(key, iv), CryptoStreamMode.Write))
- {
-
-
-
-
-
-
-
-
- bformatter.Serialize(cryptoStream, this);
- cryptoStream.Close();
- }
- }
Can anyone help please, as I am new in C Sharp. The error is being pointed to the line of code at the end of the load method (line 44), which is:
- T person = (T)formatter.Deserialize(cryptoStream);