Create a key from a password and a random salt in C#
suggest changeusing 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);
// 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. It shows how to create a key from a user-defined password, and how to create a random salt with a cryptographic random generator.
Notes:
PasswordDeriveBytesimplements PBKDF1 and is obsolete. New code should useRfc2898DeriveBytes(PBKDF2). By default,PasswordDeriveBytesuses 100 iterations to slow brute-force attacks. A random salt further strengthens the key.CryptDeriveKeyconverts the bytes fromPasswordDeriveBytesinto a key for the specified algorithm (here “TripleDES”) using the specified hash (here “SHA1”). The key size in this example is 192 bits. The initialization vector is taken from the TripleDES provider.- This mechanism is usually used to protect a stronger random key with a password. That random key then encrypts a large amount of data. You can also give several users different passwords that unlock the same data.
CryptDeriveKeydoes not support AES. See this discussion. As a workaround, create a random AES key for the data and store that AES key in a TripleDES container protected byCryptDeriveKey. That still limits security to TripleDES, does not use AES’s larger key sizes, and depends on TripleDES.
Usage: See Main() method.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents