Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

return String.Empty;

}

}

The encrypted string is returned as a Base64-encoded string. To decrypt a string encrypted with the public key, define the following AsymmetricDecryption()function. It takes in two parameters (the encrypted string and the private key) and returns the decrypted string.

static string AsymmetricDecryption(string str, string privateKey) {

try {

//---Creates a new instance of RSACryptoServiceProvider---

RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

//---Loads the private key---

RSA.FromXmlString(privateKey);

//---Decrypts the string---

byte[] DecryptedStr =

RSA.Decrypt(System.Convert.FromBase64String(str), false);

//---Converts the decrypted byte array to string---

return ASCIIEncoding.ASCII.GetString(DecryptedStr);

} catch (Exception ex) {

Console.WriteLine(ex.ToString());

return String.Empty;

}

}

The following code snippet shows how to use the AsymmetricEncryption()and AsymmetricDecryption()functions to encrypt and decrypt a string:

string publicKey, privateKey;

RSACryptoServiceProvider RSA =

new RSACryptoServiceProvider();

//---get public key---

publicKey = RSA.ToXmlString(false);

Console.WriteLine("Public key: " + publicKey);

Console.WriteLine();

//---get private and public key---

privateKey = RSA.ToXmlString(true);

Console.WriteLine("Private key: " + privateKey);

Console.WriteLine();

//---encrypt the string---

string cipherText =

AsymmetricEncryption("C# 2008 Programmer's Reference", publicKey);

Console.WriteLine("Ciphertext: " + cipherText);

Console.WriteLine();

//---decrypt the string---

Console.WriteLine("Original string: " +

AsymmetricDecryption(cipherText, privateKey));

Console.WriteLine();

You can obtain the public and private keys generated by the RSA algorithm by using the ToXmlString()method from the RSACryptoServiceProviderclass. This method takes in a Bool variable, and returns a public key if the value false is supplied. If the value true is supplied, it returns both the private and public keys.

Figure 11-8 shows the output.

Figure 118 Compressions for Stream Objects The - фото 171

Figure 11-8

Compressions for Stream Objects

The System.IO.Compressionnamespace contains classes that provide basic compression and decompression services for streams. This namespace contains two classes for data compression: DeflateStreamand GZipStream. Both support lossless compression and decompression and are designed for dealing with streams.

Compression is useful for reducing the size of data. If you have huge amount of data to store in your SQL database, for instance, you can save on disk space if you compress the data before saving it into a table. Moreover, because you are now saving smaller blocks of data into your database, the time spent in performing disk I/O is significantly reduced. The downside of compression is that it takes additional processing power from your machine (and requires additional processing time), and you need to factor in this additional time before deciding you want to use compression in your application.

Compression is extremely useful in cases where you need to transmit data over networks, especially slow and costly networks such as General Packet Radio Service (GPRS).connections. In such cases, using compression can drastically cut down the data size and reduce the overall cost of communication. Web Services are another area where using compression can provide a great advantage because XML data can be highly compressed.

But once you've decided the performance cost is worth it, you'll need help deciphering the utilization of these two compression classes, which is what this section is about.

Compression

The compression classes read data (to be compressed) from a byte array, compress it, and store the results in a Streamobject. For decompression, the compressed data stored in a Streamobject is decompressed and then stored in another Streamobject.

Let's see how you can perform compression. First, define the Compress()function, which takes in two parameters: algoand data. The first parameter specifies which algorithm to use (GZip or Deflate), and the second parameter is a byte array that contains the data to compress. A MemoryStreamobject will be used to store the compressed data. The compressed data stored in the MemoryStreamis then copied into another byte array and returned to the calling function. The Compress()function is defined as follows:

static byte[] Compress(string algo, byte[] data) {

try {

//---the ms is used for storing the compressed data---

MemoryStream ms = new MemoryStream();

Stream zipStream = null;

switch (algo) {

case "Gzip":

zipStream =

new GZipStream(ms, CompressionMode.Compress, true);

break;

case "Deflat":

zipStream =

new DeflateStream(ms, CompressionMode.Compress, true);

break;

default:

return null;

}

//---compress the data stored in the data byte array---

zipStream.Write(data, 0, data.Length);

zipStream.Close();

//---store the compressed data into a byte array---

ms.Position = 0;

byte[] c_data = new byte[ms.Length];

//---read the content of the memory stream into the byte array---

ms.Read(c_data, 0, (int)ms.Length);

return c_data;

} catch (Exception ex) {

Console.WriteLine(ex.ToString());

return null;

}

}

Decompression

The following Decompress()function decompresses the data compressed by the Compress()function. The first parameter specifies the algorithm to use, while the byte array containing the compressed data is passed in as the second parameter, which is then copied into a MemoryStreamobject.

static byte[] Decompress(string algo, byte[] data) {

try {

//---copy the data (compressed) into ms---

MemoryStream ms = new MemoryStream(data);

Stream zipStream = null;

//---decompressing using data stored in ms---

switch (algo) {

case "Gzip":

zipStream =

new GZipStream(ms, CompressionMode.Decompress, true);

break;

case "Deflat":

zipStream =

new DeflateStream(ms, CompressionMode.Decompress, true);

break;

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.