Tải bản đầy đủ - 0 (trang)
11-17. Ensure Data Integrity Using a Keyed Hash Code

11-17. Ensure Data Integrity Using a Keyed Hash Code

Tải bản đầy đủ - 0trang

CHAPTER 11 ■ SECURITY AND CRYPTOGRAPHY



Table 11-5. Keyed Hashing Algorithm Implementations



Algorithm/Class Name



Key Size (in Bits)



Hash Code Size (in Bits)



HMACMD5



Any



128



HMACRIPEMD160



Any



160



HMACSHA1



Any



160



HMACSHA256



Any



256



HMACSHA384



Any



384



HMACSHA512



Any



512



MACTripleDES



128, 192



64



As with the standard hashing algorithms, you can either create keyed hashing algorithm objects

directly or use the static factory method KeyedHashAlgorithm.Create and pass the algorithm name as an

argument. Using the factory approach allows you to write generic code that can work with any keyed

hashing algorithm implementation, but as shown in Table 11-5, MACTripleDES supports fixed key lengths

that you must accommodate in generic code.

If you use constructors to instantiate a keyed hashing object, you can pass the secret key to the

constructor. Using the factory approach, you must set the key using the Key property inherited from the

KeyedHashAlgorithm class. Then call the ComputeHash method and pass either a byte array or a

System.IO.Stream object. The keyed hashing algorithm will process the input data and return a byte

array containing the keyed hash code. Table 11-5 shows the size of the hash code generated by each

keyed hashing algorithm.



The Code

The following example demonstrates the generation of a keyed hash code from a file. The example uses

the given class to generate the keyed hash code, and then displays it to the console. The example

requires three command-line arguments: the name of the file from which the hash is calculated, the

name of the class to instantiate, and the key to use when calculating the hash.

using

using

using

using



System;

System.IO;

System.Text;

System.Security.Cryptography;



namespace Apress.VisualCSharpRecipes.Chapter11

{

class Recipe11_17

{



587



www.it-ebooks.info



CHAPTER 11 ■ SECURITY AND CRYPTOGRAPHY



public static void Main(string[] args)

{

// Create a byte array from the key string, which is the

// second command-line argument.

byte[] key = Encoding.Unicode.GetBytes(args[2]);

// Create a KeyedHashAlgorithm-derived object to generate the keyed

// hash code for the input file. Pass the byte array representing the

// key to the constructor.

using (KeyedHashAlgorithm hashAlg = KeyedHashAlgorithm.Create(args[1]))

{

// Assign the key.

hashAlg.Key = key;

// Open a FileStream to read the input file. The file name is

// specified by the first command-line argument.

using (Stream file =

new FileStream(args[0], FileMode.Open, FileAccess.Read))

{

// Generate the keyed hash code of the file's contents.

byte[] hash = hashAlg.ComputeHash(file);

// Display the keyed hash code to the console.

Console.WriteLine(BitConverter.ToString(hash));

}

}

// Wait to continue.

Console.WriteLine("\nMain method complete. Press Enter.");

Console.ReadLine();

}

}

}



Usage

Executing the following command:

Recipe11-17 Recipe11-17.exe HMACSHA1 secretKey

will display the following hash code to the console:

2E-5B-9B-2C-91-42-BA-4E-98-DF-39-F6-AE-89-B6-44-61-FB-32-E7

In contrast, executing this command:

Recipe11-17 Recipe11-17.exe HMACSHA1 anotherKey



588



www.it-ebooks.info



CHAPTER 11 ■ SECURITY AND CRYPTOGRAPHY



will display the following hash code to the console:

EF-64-79-3A-3C-A4-44-01-AD-9E-94-2A-B4-58-CF-42-84-3E-27-91



11-18. Work with Security-Sensitive Strings in Memory

Problem

You need to work with sensitive string data, such as passwords or credit card numbers, in memory, and

you need to minimize the risk of other people or processes accessing that data.



Solution

Use the class System.Security.SecureString to hold the sensitive data values in memory.



How It Works

Storing sensitive data such as passwords, personal details, and banking information in memory as

String objects is insecure for many reasons, including the following:





String objects are not encrypted.







The immutability of String objects means that whenever you change the String,

the old String value is left in memory until it is garbage-collected and later

overwritten.







Because the garbage collector is free to reorganize the contents of the managed

heap, multiple copies of your sensitive data may be present on the heap.







If part of your process address space is swapped to disk or a memory dump is

written to disk, a copy of your data may be stored on the disk.



Each of these factors increases the opportunities for others to access your sensitive data. The .NET

Framework includes the SecureString class to simplify the task of working with sensitive string data in

memory.

You create a SecureString as either initially empty or from a pointer to a character (char) array.

Then you manipulate the contents of the SecureString one character at a time using the methods

AppendChar, InsertAt, RemoveAt, and SetAt. As you add characters to the SecureString, they are

encrypted using the capabilities of the Data Protection API.



■ Note The SecureString class uses features of Data Protection API (DPAPI) and is available only on Windows

2000 SP3 and later operating system versions.



589



www.it-ebooks.info



CHAPTER 11 ■ SECURITY AND CRYPTOGRAPHY



The SecureString class also provides a method named MakeReadOnly. As the name suggests, calling

MakeReadOnly configures the SecureString to no longer allow its value to be changed. Attempting to

modify a SecureString marked as read-only results in the exception System.InvalidOperationException

being thrown. Once you have set the SecureString to read-only, it cannot be undone.

The SecureString class has a ToString method, but this does not retrieve a string representation of

the contained data. Instead, the class System.Runtime.InteropServices.Marshal implements a number

of static methods that take a SecureString object; decrypts it; converts it to a binary string, a block of

ANSI, or a block of Unicode data; and returns a System.IntPtr object that points to the converted data.

At any time, you can call the SecureString.Clear method to clear the sensitive data, and when you

have finished with the SecureString object, call its Dispose method to clear the data and free the

memory. SecureString implements System.IDisposable.



■ Note Although it might seem that the benefits of the SecureString class are limited, because there is no way

in Windows Forms applications to get such a secured string from the GUI without first retrieving an unsecured

String through a TextBox or another control, it is likely that third parties and future additions to the .NET

Framework will use the SecureString class to handle sensitive data. This is already the case in

System.Diagnostics.ProcessStartInfo, where using a SecureString, you can set the Password property to

the password of the user context in which the new process should be run.



The Code

The following example reads a username and password from the console and starts Notepad.exe as the

specified user. The password is masked on input and stored in a SecureString in memory, maximizing

the chances of the password remaining secret.

using System;

using System.Security;

using System.Diagnostics;

namespace Apress.VisualCSharpRecipes.Chapter11

{

class Recipe11_18

{

public static SecureString ReadString()

{

// Create a new emtpty SecureString.

SecureString str = new SecureString();

// Read the string from the console one

// character at a time without displaying it.

ConsoleKeyInfo nextChar = Console.ReadKey(true);



590



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

11-17. Ensure Data Integrity Using a Keyed Hash Code

Tải bản đầy đủ ngay(0 tr)

×