6.11. Encrypting a DataSet
Problem
You need to encrypt and write a DataSet to a file for storage or transmission. You also need to decrypt the file and reconstruct the DataSet.
Solution
Encrypt and decrypt the DataSet using the .NET cryptographic services, and serialize and save the encrypted DataSet to a stream (such as a file or network stream).
The solution creates a DataSet that contains a subset of data from the Person.Contact table in AdventureWorks. The contents of the DataSet are output to the console.
Next, the DataSet is encrypted to a file named symmetric.dat in the same directory as the solution file EncryptDataSet.sln and decrypted using a (symmetric) DES algorithm. The contents of the decrypted DataSet are output to the console.
Finally, the DataSet is encrypted to a file named asymmetric.dat in the same directory as the solution file EncryptDataSet.sln and decrypted using both a (symmetric) RC2 algorithm and an (asymmetric) RSA algorithm. The contents of the decrypted DataSet are output to the console.
The C# code in Program.cs in the project EncryptDataSet is shown in Example 6-11.
Example 6-11. File: Program.cs for EncryptDataSet solution
using System; using System.Data; using System.Data.SqlClient; using System.Security.Cryptography; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Xml; namespace EncryptDataSet { [Serializable( )] internal class EncryptedMessage { public byte[] Body; // RC2 encrypted ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access