Tải bản đầy đủ (.pdf) (12 trang)

Tài liệu Transmitting a DataSet Securely docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (38.13 KB, 12 trang )

[ Team LiB ]


Recipe 5.7 Transmitting a DataSet Securely
Problem
You need to securely send a DataSet over a connection that is not secure.
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 sample code contains two event handlers:
Encrypt Button.Click
The first Button.Click creates a DataSet and encrypts it using the algorithm
specified by the user and writes the encrypted DataSet to a file.
Decrypt Button.Click
The second Button.Click decrypts a file containing a DataSet previously encrypted
using an algorithm specified by the user and uses the file to recreate the DataSet
previously encrypted.
The C# code is shown in Example 5-7
.
Example 5-7. File: SecureTransmissionForm.cs
// Namespaces, variables, and constants
using System;
using System.Configuration;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Data;
using System.Data.SqlClient;



// Table name constants
private const String ORDERS_TABLE = "Orders";
private const String ORDERDETAILS_TABLE = "OrderDetails";

// Relation name constants
private const String ORDERS_ORDERDETAILS_RELATION =
"Orders_OrderDetails_Relation";

// Field name constants
private const String ORDERID_FIELD = "OrderID";

private RSACryptoServiceProvider rSAReceiver;

private const int keySize = 128;

// DES key and IV
private Byte[] dESKey = new Byte[]
{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
private Byte[] dESIV = new Byte[]
{0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18};
// RC2 key and IV
private Byte[] rC2Key = new Byte[]
{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};
private Byte[] rC2IV = new Byte[]
{0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F};
// Rijndael key and IV
private Byte[] rijndaelKey = new Byte[]

{0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F};
private Byte[] rijndaelIV = new Byte[]
{0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F};
// triple DES key and IV
private Byte[] tDESKey = new Byte[]
{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17};
private Byte[] tDESIV = new Byte[]
{0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37};

// . . .

[Serializable( )]
internal class EncryptedMessage
{
public byte[] Body; // RC2 encrypted
public byte[] Key; // RSA encrypted RC2 key
public byte[] IV; // RC2 initialization vector
}


private void encryptButton_Click(object sender, System.EventArgs e)
{
DataSet ds = new DataSet( );


SqlDataAdapter da;

// Fill the Order table and add it to the DataSet.
da = new SqlDataAdapter("SELECT * FROM Orders",
ConfigurationSettings.AppSettings["Sql_ConnectString"]);
DataTable orderTable = new DataTable(ORDERS_TABLE);
da.FillSchema(orderTable, SchemaType.Source);
da.Fill(orderTable);
ds.Tables.Add(orderTable);

// Fill the OrderDetails table and add it to the DataSet.
da = new SqlDataAdapter("SELECT * FROM [Order Details]",
ConfigurationSettings.AppSettings["Sql_ConnectString"]);
DataTable orderDetailTable = new DataTable(ORDERDETAILS_TABLE);
da.FillSchema(orderDetailTable, SchemaType.Source);
da.Fill(orderDetailTable);
ds.Tables.Add(orderDetailTable);

// Create a relation between the tables.
ds.Relations.Add(ORDERS_ORDERDETAILS_RELATION,
ds.Tables[ORDERS_TABLE].Columns[ORDERID_FIELD],
ds.Tables[ORDERDETAILS_TABLE].Columns[ORDERID_FIELD],
true);

// Clear the grid.
dataGrid.DataSource = null;

if(rSARadioButton.Checked)
{
// Asymmetric algorithm

EncryptedMessage em = new EncryptedMessage( );

// RC2 symmetric algorithm to encode the DataSet
RC2CryptoServiceProvider rC2 = new RC2CryptoServiceProvider( );
rC2.KeySize = keySize;
// Generate RC2 Key and IV.
rC2.GenerateKey( );
rC2.GenerateIV( );

// Get the receiver's RSA public key.
RSACryptoServiceProvider rSA = new RSACryptoServiceProvider( );
rSA.ImportParameters(rSAReceiver.ExportParameters(false));
try
{
// Encrypt the RC2 key and IV with the receiver's RSA
// public key.
em.Key = rSA.Encrypt(rC2.Key, false);
em.IV = rSA.Encrypt(rC2.IV, false);
}
catch(CryptographicException ex)
{
MessageBox.Show(ex.Message, "Securing Transmission",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Cursor.Current = Cursors.WaitCursor;

// Use the CryptoStream to write the encrypted DataSet to the
// MemoryStream.
MemoryStream ms = new MemoryStream( );

CryptoStream cs = new CryptoStream(ms, rC2.CreateEncryptor( ),
CryptoStreamMode.Write);
ds.WriteXml(cs, XmlWriteMode.WriteSchema);
cs.FlushFinalBlock( );
em.Body = ms.ToArray( );

cs.Close( );
ms.Close( );

// Serialize the encrypted message to a file.
Stream s = File.Open(System.IO.Path.GetTempPath( ) +
@"\rsa.dat", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter( );
bf.Serialize(s, em);
s.Close( );

Cursor.Current = Cursors.Default;

MessageBox.Show("Encryption complete.",
"Securing Transmission", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
else
{
SaveFileDialog sfd;
sfd = new SaveFileDialog( );
sfd.InitialDirectory = System.IO.Path.GetTempPath( );
sfd.Filter = "All files (*.*)|*.*";
sfd.FilterIndex = 0;


if (sfd.ShowDialog( ) == DialogResult.OK)
{
FileStream fsWrite = null;
try
{
fsWrite = new FileStream(sfd.FileName,
FileMode.Create, FileAccess.Write);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,
"Securing Transmission",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}

Cursor.Current = Cursors.WaitCursor;

// Symmetric algorithms
byte[] key = null;
byte[] iV = null;
SymmetricAlgorithm sa = null;

if(dESRadioButton.Checked)

×