密码作为AES加密/解密的密钥

问题描述 投票:0回答:1

我正在一个项目中,我必须按用户对选定的文件进行加密和解密。如何使用用户密码作为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);
    }
}
c# encryption encryption-symmetric
1个回答
0
投票

。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;
© www.soinside.com 2019 - 2024. All rights reserved.