0

hi im trying to encrypt and decrypt string value... i made it by using manual key like...

private static byte[] _salt = Encoding.ASCII.GetBytes("123456789abcdefg");

and i created key and iv like

Rfc2898DeriveBytes rfcDeriveBytes = new Rfc2898DeriveBytes(password, _salt);
rijndaelManaged = new RijndaelManaged();
rijndaelManaged.Key = rfcDeriveBytes.GetBytes(rijndaelManaged.KeySize / 8);
rijndaelManaged.IV = rfcDeriveBytes.GetBytes(rijndaelManaged.BlockSize / 8);

but i wanna generate the same key dynamically... i mean how can i generate _salt dynamically...

tshepang
  • 12,111
  • 21
  • 91
  • 136
serim urhan
  • 31
  • 1
  • 5
  • It's not clear what you mean by "create the same key dynamically". What do you want to be dynamic? Are you just talking about generating a *random* key? Note that you haven't told us anything about `rfcDeriveBytes`. – Jon Skeet Nov 29 '10 at 09:29
  • Please explain what you mean with 'same' and 'dynamically' here – H H Nov 29 '10 at 09:30
  • i wanna use key generator instead of _salt – serim urhan Nov 29 '10 at 09:36

2 Answers2

2

The Rfc2898DeriveBytes class can generate a random salt for you - just pass the required salt size to the appropriate constructor. And don't forget to store the generated salt somewhere safe - it can't be deterministically regenerated, and without it you won't be able to recreate your key and IV for decryption.

string password = GetPasswordFromUserInputOrWherever();

using (var deriveBytes = new Rfc2898DeriveBytes(password, 16))  // 16 byte salt
{
    byte[] salt = deriveBytes.Salt;

    // now save the salt somewhere safe
    // you'll need it to generate the same byte sequence when decrypting

    using (var rijndael = new RijndaelManaged())
    {
        rijndael.Key = deriveBytes.GetBytes(rijndael.KeySize / 8);
        rijndael.IV = deriveBytes.GetBytes(rijndael.BlockSize / 8);

        // encrypt...
    }
}

And then to decrypt:

string password = GetPasswordFromUserInputOrWherever();
byte[] salt = GetSaltFromWhereverYouPreviouslySavedIt();

using (var deriveBytes = new Rfc2898DeriveBytes(password, salt))
using (var rijndael = new RijndaelManaged())
{
    rijndael.Key = deriveBytes.GetBytes(rijndael.KeySize / 8);
    rijndael.IV = deriveBytes.GetBytes(rijndael.BlockSize / 8);

    // decrypt...
}
LukeH
  • 263,068
  • 57
  • 365
  • 409
1

The 'salt' is not secret, you can include it with the encrypted data. You cannot use different salts while encrypting/decrypting, and to be effective you should use a different salt for each message.

You can use the System.Security.Cryptography.RandomNumberGenerator class to create a Salt.

H H
  • 263,252
  • 30
  • 330
  • 514
  • Note that `Rfc2898DeriveBytes` can generate a salt for you (using `RandomNumberGenerator` internally) if you ask it to. – LukeH Nov 29 '10 at 10:40