限制rijndaelmanaged算法密钥大小?

时间:2013-08-07 06:19:58

标签: c# asp.net

我使用rijndaelmanaged algoritham进行密码加密

有没有办法限制加密文本密钥的大小?

例如:1,ABC - 加密密钥大小10

  2, ABCDHGF - Encrypted key size 10

意味着固定尺寸!!

2 个答案:

答案 0 :(得分:2)

如果您不需要从加密数据中取回密码,则可以使用哈希算法。首先计算密码的哈希值,然后加密此哈希值。由于哈希值具有固定长度,因此加密数据将具有固定长度。当您需要检查密码时,解密加密值并从输入的密码重新计算哈希值,然后检查它们是否匹配。

例如在注册页面上

var encryptedPwd = Encrypt(ComputeHash(txtPassword.Text));
Save(txtUsername.Text, encryptedPwd);

在登录页面上

var encryptedPwd = SelectPwd(txtUsername.Text);
var pwdHash1 = Decrypt(encryptedPwd);
var pwdHash2 = ComputeHash(txtPassword.Text);

if (AreEqual(pwdHash1, pwdHash2))
   // Login OK!
else
   // Login fail

另一种选择可能是制作自定义填充。假设您的密码最大长度为16个字符。然后你可以用一些固定的字符填充每个密码到16个字符。然后加密这个填充密码。验证会更容易,但使用哈希会更安全一些。

注册

var encryptedPwd = Encrypt(txtPassword.Text.PadRight(16, 'X'));
Save(txtUsername.Text, encryptedPwd);

登录

var encryptedPwd = SelectPwd(txtUsername.Text);
var pwd1 = Decrypt(encryptedPwd);
var pwd2 = txtPassword.Text.PadRight(16, 'X');

if (AreEqual(pwd1, pwd2))
   // Login OK!
else
   // Login fail

答案 1 :(得分:1)

建议使用密码强化算法,而不是使用简单的散列,如Rfc2898中指定的算法

string password = "P@$$w0rd";
byte[] salt = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }; // this is fixed... It would be better you used something different for each user

// You can raise 1000 to greater numbers... more cycles = more security. Try
// balancing speed with security.
Rfc2898DeriveBytes pwdGen = new Rfc2898DeriveBytes(password, salt, 1000);

// generate key and iv
byte[] key = pwdGen.GetBytes(16);
byte[] iv = pwdGen.GetBytes(16);


byte[] encrypted;

{
    RijndaelManaged rijndaelCipher = new RijndaelManaged();
    rijndaelCipher.Key = key;
    rijndaelCipher.IV = iv;

    // Or your data
    byte[] data = System.Text.Encoding.UTF8.GetBytes("hello world");
    var encryptor = rijndaelCipher.CreateEncryptor();

    encrypted = encryptor.TransformFinalBlock(data, 0, data.Length);
}

{
    RijndaelManaged rijndaelCipher = new RijndaelManaged();
    rijndaelCipher.Key = key;
    rijndaelCipher.IV = iv;

    var decryptor = rijndaelCipher.CreateDecryptor();

    byte[] decrypted = decryptor.TransformFinalBlock(encrypted, 0, encrypted.Length);

    // this if you are encrypting text, otherwise decrypted is already your data
    string text = System.Text.Encoding.UTF8.GetString(decrypted);
}