[英]Password as key for AES Encryption/Decryption
我正在做一个项目,我必须加密和解密用户选择的文件。 如何使用用户的密码作为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);
}
}
.net 中的 AES 默认使用 256 位密钥和 128 位 IV。
SHA256 和 MD5 hash 算法分别创建 256 位和 128 位 hash。
嗯。
byte[] passwordBytes = UE.GetBytes(password);
byte[] aesKey = SHA256Managed.Create().ComputeHash(passwordBytes);
byte[] aesIV = MD5.Create().ComputeHash(passwordBytes);
AES.Key = aesKey;
AES.IV = aesIV;
AES.Mode = CipherMode.CBC;
AES.Padding = PaddingMode.PKCS7;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.