Introduction
This article shows you how you can derive secure and strong keys for encryption in symmetric algorithms.
I assume you have knowledge on cryptography. You can read a good introductory article on encryption here.
Deriving a Key from a Password
Suppose you want to encrypt sensitive information of users of your application. You don't want anybody to be able to decrypt this data. So you decide to encrypt using Rijndael, a good symmetric algorithm. But Rijndael needs at least a 128 bit key. You also want to store this key in a secure environment.
I have written a complementary class to the EncDec
described in this article.
This class generates Keys
and IV
, derives them from passwords, and stores them in a secure manner.
Here is the full implementation:
using System.Security.Cryptography;
public sealed class GenKeys
{
public static byte[] DeriveKeyFromPassword(string password, int size)
{
return DeriveKey(password, GenSalt(8), size/8);
}
public byte[] GenIV(int size)
{
return GenSalt(size/8);
}
private static byte[] GenSalt(int size)
{
RandomNumberGenerator rng = RandomNumberGenerator.Create();
byte[] result = new byte[size];
rng.GetNonZeroBytes (result);
return result;
}
private static byte[] DeriveKey(string password, byte[] salt, int size)
{
PasswordDeriveBytes pder = new PasswordDeriveBytes(password, salt);
pder.IterationCount = 100;
pder.HashName = "SHA1";
return pder.GetBytes (size);
}
}
Now you can use this class with EncDec
in this way:
byte[] iv = GenKeys.GenIV(128);
byte[] key = GenKeys.DeriveKeyFromPassword("my own private password", 128);
byte[] data = {......};
EncDec.Encrypt(data, key, iv)
EncDec
has methods that use PasswordDerivedBytes
class, but in the implementation, the salt is hard coded. Using GenKeys
class, you can generate and store the keys outside your program.
One trick is to use an automatic generated password, for example the MAC address of your Ethernet card and use it for deriving a password, then generate the IV
deriving from another automatically generated, like the CPU ID, size of your executable, the primary Key
of a record in a table, etc.
The Search of a Secure Key Storage
I will start writing in my blog about this topic, and I will investigate ways to store the generated keys in a safe manner.
I will update this article when my investigations give acceptable results.
See you soon.
Visit my blog here.
History
- 25th July, 2005: Initial post