gpt4 book ai didi

c# - Rfc2898DeriveBytes 的输出取决于什么,应该如何处理盐?

转载 作者:太空宇宙 更新时间:2023-11-03 23:00:37 28 4
gpt4 key购买 nike

public string Encrypt(string Code)
{
string result = string.Empty;
byte[] encryptResult = null;
var CodeInByte = Encoding.ASCII.GetBytes(Code);

try
{
using (MemoryStream memo = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = KeySize;
AES.BlockSize = BlockSize;

var key = new Rfc2898DeriveBytes(CodeInByte, salt, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);

AES.Mode = CipherMode.CBC;

using (var encrypt = new CryptoStream(memo, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
encrypt.Write(CodeInByte, 0, CodeInByte.Length);
encrypt.Close();
}

encryptResult = memo.ToArray();
}
}

result = Convert.ToBase64String(encryptResult);
return result;
}
catch (Exception err)
{
MsgCode = 99;
MsgDesc = err.Message;
return string.Empty;
}
}

只是一个简单的字符串AES加密方法

我想问的一点,在生成 key 的时候,在

var key = new Rfc2898DeriveBytes(CodeInByte, salt, 1000);

key 是由输入的字符串生成的,还是只是一个随机生成的字节数组?

并且,盐是否需要是静态的

最佳答案

作为documentation on MSDN建议:

Rfc2898DeriveBytes takes a password, a salt, and an iteration count, and then generates keys through calls to the GetBytes method.

换句话说,它将使用您提供的输入参数派生字节。如果你给它不同的参数,派生的 key 就会不同。如果您给它相同的参数,它将生成相同的字节。

对称加密算法(例如 AES)需要固定长度的 key - 在本例中为 16 字节的 AES128。但是,您不想强制密码长度固定,因为这会使它们更容易受到攻击。您可能还需要比可行密码更长的 key - 例如,AES256 需要 32 字节的 key 。最后,密码往往是字母数字并且可能有一些符号,而加密 key 由范围为 0x00-0xFF 的字节组成,如果您将加密 key 设置为 32 个字符的 ASCII 密码,那么您将大大缩小范围因为可打印的 ASCII 字符范围远小于 0x00-0xFF。

出于这个原因,您希望从给定的密码中导出加密 key ,这样您就可以获得所需长度的强 key 。这就是 Rfc2898DeriveBytes 的用武之地。

关于c# - Rfc2898DeriveBytes 的输出取决于什么,应该如何处理盐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43252590/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com