开发者

how to generate the same key when using crypto c# 4.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 th开发者_JAVA百科e same key dynamically... i mean how can i generate _salt dynamically...


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...
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜