C # Crypter un fichier sérialisé avant d’écrire sur le disque

Disons que mon programme a une classe appelée “client” et que la classe client est sérialisable afin que je puisse le lire et l’écrire sur le disque. La classe de clients contient des informations sensibles que je veux chiffrer. La seule façon pour moi de protéger le fichier serait de:

1-Sérialiser le fichier sur le disque

2-rouvrir et charger le fichier

3-Crypter le fichier

4-réécrire le fichier sur le disque

Cela fonctionnerait, mais le fichier risquerait d’être intercepté dans son état non chiffré et, de plus, cela serait vraiment inefficace.

J’aimerais plutôt:

1-Créer un fichier en mémoire

2-Crypter le fichier en mémoire

3-Write fichier crypté sur le disque

Est-ce possible? Si c’est comment? Merci d’avance.

Outre les préoccupations exprimées dans les commentaires, si tout ce que vous demandez, c’est comment utiliser les octets en mémoire et les écrire une seule fois dans le fichier, il vous suffit de sérialiser d’abord votre object dans un stream de mémoire. Cryptez ces octets et écrivez-les dans le fichier.

using (var fileStream = File.OpenWrite(theFileName)) using (var memoryStream = new MemoryStream()) { // Serialize to memory instead of to file var formatter = new BinaryFormatter(); formatter.Serialize(memoryStream, customer); // This resets the memory stream position for the following read operation memoryStream.Seek(0, SeekOrigin.Begin); // Get the bytes var bytes = new byte[memoryStream.Length]; memoryStream.Read(bytes, 0, (int)memoryStream.Length); // Encrypt your bytes with your chosen encryption method, and write the result instead of the source bytes var encryptedBytes = yourCrypto.Encrypt(bytes); fileStream.Write(encryptedBytes, 0, encryptedBytes.Length); } 

Vous pouvez utiliser CryptoStream pour effectuer le chiffrement en même temps que vous sérialisez la classe dans un fichier:

 byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8 }; // Where to store these keys is the sortingcky part, // you may need to obfuscate them or get the user to input a password each time byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 }; ssortingng path = @"C:\path\to.file"; DESCryptoServiceProvider des = new DESCryptoServiceProvider(); // Encryption using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write)) using (var cryptoStream = new CryptoStream(fs, des.CreateEncryptor(key, iv), CryptoStreamMode.Write)) { BinaryFormatter formatter = new BinaryFormatter(); // This is where you serialize the class formatter.Serialize(cryptoStream, customClass); } // Decryption using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (var cryptoStream = new CryptoStream(fs, des.CreateDecryptor(key, iv), CryptoStreamMode.Read)) { BinaryFormatter formatter = new BinaryFormatter(); // This is where you deserialize the class CustomClass deserialized = (CustomClass)formatter.Deserialize(cryptoStream); } 

C’est tout à fait possible

Disons que votre classe ressemble à

 public class Customer { public ssortingng Name{get;set;} public int salary {get;set;} } 

Vous pouvez chiffrer les données contenues dans les propriétés de l’object afin que customer.Name = ‘ABC’ devienne client.Name = ‘WQW’

que le sérialiser.

Lors de la désérialisation, lorsque vous devez afficher les données, vous devez les déchiffrer avant de les présenter à l’utilisateur.

espérons que cette aide

Je créerais une classe de sérialisation qui offre une propriété. en le lisant (en donnant un nom de fichier), on renvoie les objects désérialisés. En y écrivant (en donnant également un nom de fichier), l’object est sérialisé. J’ai ajouté une deuxième propriété avec un mot de passe Ssortingng. Lors de son utilisation, vous pouvez chiffrer la chaîne d’object sérialisée et la lettre nwrite sur le disque ou lors de la lecture de celle-ci. 1. chiffrez, puis désérialisez.

Pour chiffrer, je recommanderais une fonction de hachage à partir du mot de passe au lieu de l’utiliser directement. Malheureusement, je n’ai qu’un exemple de code sur vb.net:

 Function Encrypt(ByVal data As Ssortingng, ByVal password As Ssortingng) As Ssortingng Dim pdb As New Rfc2898DeriveBytes(password, Salt) Dim alg As Rijndael = Rijndael.Create() alg.Key = pdb.GetBytes(32) alg.IV = pdb.GetBytes(16) Dim ms As New IO.MemoryStream Dim cs As New CryptoStream(ms, alg.CreateEncryptor, CryptoStreamMode.Write) cs.Write(System.Text.Encoding.Default.GetBytes(data), 0, data.Length) cs.Close() ms.Close() Return Convert.ToBase64Ssortingng(ms.ToArray) End Function Private Salt As Byte() = {100, 86, 34, 53, 11, 224, 145, 123, _ 237, 213, 12, 124, 45, 65, 71, 127, _ 135, 165, 234, 164, 127, 234, 231, 211, _ 10, 9, 114, 234, 44, 63, 75, 12} Function Decrypt(ByVal data As Ssortingng, ByVal password As Ssortingng) As Ssortingng Dim pdb As New Rfc2898DeriveBytes(password, Salt) Dim alg As Rijndael = Rijndael.Create() alg.Key = pdb.GetBytes(32) alg.IV = pdb.GetBytes(16) Dim ms As New IO.MemoryStream Dim cs As New CryptoStream(ms, alg.CreateDecryptor, CryptoStreamMode.Write) cs.Write(Convert.FromBase64Ssortingng(data), 0, Convert.FromBase64Ssortingng(data).Length) cs.Close() ms.Close() Return System.Text.Encoding.Default.GetSsortingng(ms.ToArray) End Function 

et

 Function EncryptWithHash(ByVal data As Ssortingng, ByVal passToHash As Ssortingng) As Ssortingng Dim _hash As Ssortingng = getMd5Hash(passToHash) Dim _result As Ssortingng = Encrypt(data, _hash) Return _result End Function Function DecryptWithHash(ByVal data As Ssortingng, ByVal passToHash As Ssortingng) As Ssortingng Dim _hash As Ssortingng = getMd5Hash(passToHash) Dim _result As Ssortingng = Encrypt(data, _hash) Return _result End Function Function getMd5Hash(ByVal input As Ssortingng) As Ssortingng ' Create a new instance of the MD5CryptoServiceProvider object. Dim md5Hasher As New MD5CryptoServiceProvider() ' Convert the input ssortingng to a byte array and compute the hash. Dim data As Byte() = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input)) ' Create a new Ssortingngbuilder to collect the bytes ' and create a ssortingng. Dim sBuilder As New SsortingngBuilder() ' Loop through each byte of the hashed data ' and format each one as a hexadecimal ssortingng. Dim i As Integer For i = 0 To data.Length - 1 sBuilder.Append(data(i).ToSsortingng("x2")) Next i ' Return the hexadecimal ssortingng. Return sBuilder.ToSsortingng() End Function 

la propriété dans mon code a Get:

  Dim _dataC As Ssortingng = ReadFile(filename) Dim _dataR As Ssortingng = Crypt.Decrypt(_dataC, password) Dim _result = tmpS.ReadSsortingng(_dataR) 

Et mettre:

  Dim _tmpS As New Custom.Serialization(Of Object) Dim _tmpRaw As Ssortingng = _tmpS.WriteSsortingng(value) Dim _tmpCrypt As Ssortingng = Crypt.Encrypt(_tmpRaw, password) WriteFile(tmpPath, _tmpCrypt) 

vous devrez définir votre propre sérialisation et lire / écrire des fichiers:

 My.Computer.FileSystem.WriteAllText(filename, data, False) _result = My.Computer.FileSystem.ReadAllText(FileName)