【发布时间】:2020-04-11 16:08:08
【问题描述】:
我正在做一个项目,我必须对用户选择的文件进行加密和解密。如何使用用户的密码作为 AES 加密/解密的密钥?现在他们可以输入 8 或 16 个字符长的密码。我不想强制用户指定 8 或 16 个字符的密码。
public static void EncryptFile(string file, string password)
{
try
{
string outputFile = Path.GetFileNameWithoutExtension(file) + "-encrypted" + Path.GetExtension(file);
byte[] fileContent = File.ReadAllBytes(file);
UnicodeEncoding UE = new UnicodeEncoding();
using (AesCryptoServiceProvider AES = new AesCryptoServiceProvider())
{
AES.Key = UE.GetBytes(password);
AES.IV = new byte[16];
AES.Mode = CipherMode.CBC;
AES.Padding = PaddingMode.PKCS7;
using (MemoryStream memoryStream = new MemoryStream())
{
CryptoStream cryptoStream = new CryptoStream(memoryStream, AES.CreateEncryptor(), CryptoStreamMode.Write);
cryptoStream.Write(fileContent, 0, fileContent.Length);
cryptoStream.FlushFinalBlock();
File.WriteAllBytes(outputFile, memoryStream.ToArray());
}
}
}
catch (Exception ex)
{
MessageBox.Show("Exception thrown while encrypting the file!" + "\n" + ex.Message);
}
}
【问题讨论】:
-
您通常不会使用密码作为密钥,而是首先通过密钥派生函数(如 pkdf2)传递它。
标签: c# encryption encryption-symmetric