Tải bản đầy đủ - 0 (trang)
11-14. Calculate the Hash Code of a Password

11-14. Calculate the Hash Code of a Password

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

CHAPTER 11 ■ SECURITY AND CRYPTOGRAPHY



■ Caution You should never store a user’s plain text password, because it is a major security risk and one that

most users would not appreciate, given that many of them will use the same password to access multiple

systems.



How It Works

Hashing algorithms are one-way cryptographic functions that take plain text of variable length and

generate a fixed-size numeric value. They are one-way because it’s nearly impossible to derive the

original plain text from the hash code. Hashing algorithms are deterministic; applying the same hashing

algorithm to a specific piece of plain text always generates the same hash code. This makes hash codes

useful for determining if two blocks of plain text (passwords in this case) are the same. The design of

hashing algorithms ensures that the chance of two different pieces of plain text generating the same

hash code is extremely small (although not impossible). In addition, there is no correlation between the

similarity of two pieces of plain text and their hash codes; minor differences in the plain text cause

significant differences in the resulting hash codes.

When using passwords to authenticate a user, you are not concerned with the content of the

password that the user enters. You need to know only that the entered password matches the password

that you have recorded for that user in your accounts database.

The nature of hashing algorithms makes them ideal for storing passwords securely. When the user

provides a new password, you must create the hash code of the password and store it, and then discard

the plain text password. Each time the user tries to authenticate with your application, calculate the

hash code of the password that user provides and compare it with the hash code you have stored.



■ Note People regularly ask how to obtain a password from a hash code. The simple answer is that you cannot.

The whole purpose of a hash code is to act as a token that you can freely store without creating security holes. If a

user forgets a password, you cannot derive it from the stored hash code. Rather, you must either reset the account

to some default value or generate a new password for the user.



Generating hash codes is simple in the .NET Framework. The abstract class HashAlgorithm provides

a base from which all concrete hashing algorithm implementations derive. The .NET Framework class

library includes the seven hashing algorithm implementations listed in Table 11-4; each implementation

class is a member of the System.Security.Cryptography namespace. The classes with names ending in

CryptoServiceProvider wrap functionality provided by the native Win32 CryptoAPI, whereas those with

names ending in Managed are fully implemented in managed code.



578



www.it-ebooks.info



CHAPTER 11 ■ SECURITY AND CRYPTOGRAPHY



Table 11-4. Hashing Algorithm Implementations



Algorithm Name



Class Name



Hash Code Size (in Bits)



MD5



MD5CryptoServiceProvider



128



RIPEMD160 or RIPEMD-160



RIPEMD160Managed



160



SHA or SHA1



SHA1CryptoServiceProvider



160



SHA1Managed



SHA1Managed



160



SHA256 or SHA-256



SHA256Managed



256



SHA384 or SHA-384



SHA384Managed



384



SHA512 or SHA-512



SHA512Managed



512



Although you can create instances of the hashing algorithm classes directly, the HashAlgorithm base

class is a factory for the concrete implementation classes that derive from it. Calling the static method

HashAlgorithm.Create will return an object of the specified type. Using the factory approach allows you

to write generic code that can work with any hashing algorithm implementation. Note that unlike in

recipe 11-13, you do not pass the class name as parameter to the factory; instead, you pass the algorithm

name.

Once you have a HashAlgorithm object, its ComputeHash method accepts a byte array argument

containing plain text and returns a new byte array containing the generated hash code. Table 11-4 shows

the size of hash code (in bits) generated by each hashing algorithm class.



■ Note The SHA1Managed algorithm cannot be implemented using the factory approach. It must be instantiated

directly.



The Code

The example shown here demonstrates the creation of a hash code from a string, such as a password.

The application expects two command-line arguments: the name of the hashing algorithm to use and

the string from which to generate the hash. Because the HashAlgorithm.ComputeHash method requires a

byte array, you must first byte-encode the input string using the class System.Text.Encoding, which

provides mechanisms for converting strings to and from various character-encoding formats.

using System;

using System.Text;

using System.Security.Cryptography;



579



www.it-ebooks.info



CHAPTER 11 ■ SECURITY AND CRYPTOGRAPHY



namespace Apress.VisualCSharpRecipes.Chapter11

{

class Recipe11_14

{

public static void Main(string[] args)

{

// Create a HashAlgorithm of the type specified by the first

// command-line argument.

HashAlgorithm hashAlg = null;

if (args[0].CompareTo("SHA1Managed") == 0)

{

hashAlg = new SHA1Managed();

}

else

{

hashAlg = HashAlgorithm.Create(args[0]);

}

using (hashAlg)

{

// Convert the password string, provided as the second

// command-line argument, to an array of bytes.

byte[] pwordData = Encoding.Default.GetBytes(args[1]);

// Generate the hash code of the password.

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

// Display the hash code of the password to the console.

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

// Wait to continue.

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

Console.ReadLine();

}

}

}

}



Usage

Running the following command:

Recipe11-14 SHA1 ThisIsMyPassword

will display the following hash code to the console:

30-B8-BD-58-29-88-89-00-D1-5D-2B-BE-62-70-D9-BC-65-B0-70-2F



580



www.it-ebooks.info



CHAPTER 11 ■ SECURITY AND CRYPTOGRAPHY



In contrast, executing this command:

Recipe11-14 RIPEMD-160 ThisIsMyPassword

will display the following hash code:

0C-39-3B-2E-8A-4E-D3-DD-FB-E3-C8-05-E4-62-6F-6B-76-7C-7A-49



11-15. Calculate the Hash Code of a File

Problem

You need to determine whether the contents of a file have changed over time.



Solution

Create a cryptographic hash code of the file’s contents using the ComputeHash method of the

System.Security.Cryptography.HashAlgorithm class. Store the hash code for future comparison against

newly generated hash codes.



How It Works

As well as allowing you to store passwords securely (discussed in recipe 11-14), hash codes provide an

excellent means of determining if a file has changed. By calculating and storing the cryptographic hash

of a file, you can later recalculate the hash of the file to determine if the file has changed in the interim. A

hashing algorithm will produce a very different hash code even if the file has been changed only slightly,

and the chances of two different files resulting in the same hash code are extremely small.



■ Caution Standard hash codes are not suitable for sending with a file to ensure the integrity of the file’s

contents. If someone intercepts the file in transit, that person can easily change the file and recalculate the hash

code, leaving the recipient none the wiser. Recipe 11-17 discusses a variant of the hash code—a keyed hash

code—that is suitable for ensuring the integrity of a file in transit.



The HashAlgorithm class makes it easy to generate the hash code of a file. First, instantiate one of the

concrete hashing algorithm implementations derived from the HashAlgorithm class. To instantiate the

desired hashing algorithm class, pass the name of the hashing algorithm to the HashAlgorithm.Create

method, as described in recipe 11-14. See Table 11-4 for a list of valid hashing algorithm names. Then,

instead of passing a byte array to the ComputeHash method, you pass a System.IO.Stream object



581



www.it-ebooks.info



CHAPTER 11 ■ SECURITY AND CRYPTOGRAPHY



representing the file from which you want to generate the hash code. The HashAlgorithm object handles

the process of reading data from the Stream and returns a byte array containing the hash code for the file.



The Code

The example shown here demonstrates the generation of a hash code from a file. The application

expects two command-line arguments: the name of the hashing algorithm to use and the name of the

file from which the hash is calculated.

using System;

using System.IO;

using System.Security.Cryptography;

namespace Apress.VisualCSharpRecipes.Chapter11

{

class Recipe11_15

{

public static void Main(string[] args)

{

// Create a HashAlgorithm of the type specified by the first

// command-line argument.

using (HashAlgorithm hashAlg = HashAlgorithm.Create(args[0]))

{

// Open a FileStream to the file specified by the second

// command-line argument.

using (Stream file =

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

{

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

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

// Display the hash code of the file to the console.

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

}

// Wait to continue.

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

Console.ReadLine();

}

}

}

}



Usage

Running this command:

Recipe11-15 SHA1 Recipe11-15.exe

will display the following hash code to the console:



582



www.it-ebooks.info



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

11-14. Calculate the Hash Code of a Password

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

×