Good day. How can you implement property encryption when an object is serialized? For example:

From this:

<?xml version="1.0"?> <AppParameters xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Data> <settings1>123</settings1> <settings2>567</settings2> </Data> </AppParameters> 

Receive:

 <?xml version="1.0"?> <AppParameters xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Data> sadasd1ds1dsadasdfgsfgsd /*зашифрованные данные всех полей класса Data*/ </Data> </AppParameters> 
  • While you wait for answers, I can advise you to read about prefuscators - Pyrejkee
  • And where did you get the idea that this is still serialization? Then take the whole file and encrypt it with any algorithm. - Monk
  • @Monk, perhaps there are methods to encrypt the properties of the object when it is serialized, if not, then I agree, it is more logical to use encryption of the entire file. - Gardes

2 answers 2

If you want to encrypt a file, but leave it text / xml - then you should look towards the class System.Security.Cryptography.Xml.EncryptedXml

It allows you to encrypt individual elements (using RSA or any SymmetricAlgorithm ) + can decrypt the entire file:

 static void Main(string[] args) { var xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.Load(@"C:\Temp\in.xml"); Encrypt(Create3DES("MyPasswword"), xmlDoc); xmlDoc.Save(@"C:\Temp\enc.xml"); Decrypt(Create3DES("MyPasswword"), xmlDoc); xmlDoc.Save(@"C:\Temp\dec.xml"); } private static TripleDESCryptoServiceProvider Create3DES(string password) { TripleDESCryptoServiceProvider encKey = new TripleDESCryptoServiceProvider(); MD5 md5 = new MD5CryptoServiceProvider(); encKey.Key = md5.ComputeHash(Encoding.Unicode.GetBytes(password)); return encKey; } private static void Decrypt(SymmetricAlgorithm key, XmlDocument xmlDoc) { var encryptedXml = new EncryptedXml(xmlDoc); encryptedXml.AddKeyNameMapping("MyKey", key); encryptedXml.DecryptDocument(); } private static void Encrypt(SymmetricAlgorithm key, XmlDocument xmlDoc) { var encryptedXml = new EncryptedXml(xmlDoc); var inputElement = (XmlElement)xmlDoc.SelectSingleNode("//Data"); encryptedXml.AddKeyNameMapping("MyKey", key); var ed = encryptedXml.Encrypt(inputElement, "MyKey"); EncryptedXml.ReplaceElement(inputElement, ed, false); } 

    I think it's best to completely encrypt the file. An example can be found here.