限制rijndaelmanaged算法密钥大小

本文关键字:密钥 算法 rijndaelmanaged 限制 | 更新日期: 2023-09-27 18:26:38

我正在使用rijndaelmanaged算法进行密码加密

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

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

  2, ABCDHGF - Encrypted key size 10

表示固定大小!!

限制rijndaelmanaged算法密钥大小

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

例如在注册页面上

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

建议不要使用简单的哈希,而是使用密码增强算法,如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);
}