Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
DotNETFrameworkNotesForProfessionals.pdf
Скачиваний:
32
Добавлен:
20.05.2023
Размер:
1.82 Mб
Скачать

In a real encryption scenario, you need to choose a proper cipher mode (can be assigned to the Mode property by selecting a value from the CipherMode enumeration). Never use the CipherMode.ECB (electronic codebook mode), since this procuces a weak cypher stream

To create a good (and not a weak) Key, either use a cryptographic random generator or use the example above (Create a Key from a Password). The recommended KeySize is 256 bit. Supported key sizes are available via the LegalKeySizes property.

To initialize the initialization vector IV, you can use a SALT as shown in the example above (Random SALT)

Supported block sizes are available via the SupportedBlockSizes property, the block size can be assigned via the BlockSize property

Usage: see Main() method.

Section 49.4: Create a Key from a Password / Random SALT (in C#)

using System;

using System.Security.Cryptography; using System.Text;

public class PasswordDerivedBytesExample

{

public static void Main(String[] args)

{

// Get a password from the user.

Console.WriteLine("Enter a password to produce a key:");

byte[] pwd = Encoding.Unicode.GetBytes(Console.ReadLine());

byte[] salt = CreateRandomSalt(7);

// Create a TripleDESCryptoServiceProvider object.

TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

try

{

Console.WriteLine("Creating a key with PasswordDeriveBytes...");

//Create a PasswordDeriveBytes object and then create

//a TripleDES key from the password and salt.

PasswordDeriveBytes pdb = new PasswordDeriveBytes(pwd, salt);

//Create the key and set it to the Key property

//of the TripleDESCryptoServiceProvider object.

tdes.Key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, tdes.IV);

Console.WriteLine("Operation complete.");

}

catch (Exception e)

{

Console.WriteLine(e.Message);

}

finally

{

// Clear the buffers

ClearBytes(pwd);

ClearBytes(salt);

GoalKicker.com – .NET Framework Notes for Professionals

158

// Clear the key. tdes.Clear();

}

Console.ReadLine();

}

#region Helper methods

///<summary>

///Generates a random salt value of the specified length.

///</summary>

public static byte[] CreateRandomSalt(int length)

{

// Create a buffer byte[] randBytes;

if (length >= 1)

{

randBytes = new byte[length];

}

else

{

randBytes = new byte[1];

}

//Create a new RNGCryptoServiceProvider.

RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();

//Fill the buffer with random bytes.

rand.GetBytes(randBytes);

// return the bytes. return randBytes;

}

///<summary>

///Clear the bytes in a buffer so they can't later be read from memory.

///</summary>

public static void ClearBytes(byte[] buffer)

{

//Check arguments. if (buffer == null)

{

throw new ArgumentNullException("buffer");

}

//Set each byte in the buffer to 0.

for (int x = 0; x < buffer.Length; x++)

{

buffer[x] = 0;

}

}

#endregion

}

This example is taken from MSDN.

It is a console demo, and it shows how to create a secure key based on a user-defined password, and how to create a random SALT based on the cryptographic random generator.

GoalKicker.com – .NET Framework Notes for Professionals

159

Notes:

The built-in function PasswordDeriveBytes uses the standard PBKDF1 algorithm to generate a key from the password. Per default, it uses 100 iterations to generate the key to slow down brute force attacks. The SALT generated randomly further strenghens the key.

The function CryptDeriveKey converts the key generated by PasswordDeriveBytes into a key compatible with the specified encryption algorithm (here "TripleDES") by using the specified hash algorithm (here "SHA1"). The keysize in this example is 192 bytes, and the initialization vector IV is taken from the triple-DES crypto provider

Usually, this mechanism is used to protect a stronger random generated key by a password, which encrypts large amount of data. You can also use it to provide multiple passwords of di erent users to give access to the same data (being protected by a di erent random key).

Unfortunately, CryptDeriveKey does currently not support AES. See here.

NOTE: As a workaround, you can create a random AES key for encryption of the data to be protected with AES and store the AES key in a TripleDES-Container which uses the key generated by CryptDeriveKey. But that limits the security to TripleDES, does not take advantage of the larger keysizes of AES and creates a dependency to TripleDES.

Usage: See Main() method.

GoalKicker.com – .NET Framework Notes for Professionals

160