密码作为 AES 的密钥 Encryption/Decryption

Password as key for AES Encryption/Decryption

我正在做一个项目,我必须对用户选择的文件进行加密和解密。如何使用用户的密码作为 AES encryption/decryption 的密钥?现在他们可以输入 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 哈希算法分别创建 256 位和 128 位哈希。

嗯嗯。

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;