这是我第一次使用 AES 加密,我有些困惑。我正在加密一些敏感数据(没有密码,只有姓名、地址、身份证号等)。我找到了一个很好的例子,说明如何在我的应用程序中实现 AES。我了解我提供了密码、盐、哈希算法和密码迭代来制作密钥。然后这会创建密文。我有几个问题是为什么 KeySize 会减少 8 倍?如果我想让其他人解密这个,我需要给他们什么?每次我加密新东西时,密码、盐和 IV 是否应该不同,如果是这种情况,我如何确保我想使用此信息的其他人始终知道这一点?
public static string Encrypt(string PlainText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize)
{
try
{
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
RijndaelManaged SymmetricKey = new RijndaelManaged();
SymmetricKey.Mode = CipherMode.CBC;
ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes);
MemoryStream MemStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write);
cryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] CipherTextBytes = MemStream.ToArray();
MemStream.Close();
cryptoStream.Close();
MemStream.Dispose();
cryptoStream.Dispose();
Encryptor.Dispose();
return Convert.ToBase64String(CipherTextBytes);
}
catch (Exception ex)
{
throw ex;
}
}