AES在解密时使用\ 0填充字节数组

时间:2016-07-04 14:24:12

标签: c# string aes

每当我解密文件时,我最终都会在每个字符之间使用\ 0(这是一个文本文件)原始文件很好,解密成功没有错误。

当我打开文件时; "你好"将成为" h \ 0e \ 0l \ 0 ..."

这是我的解密函数:(我想出了将字节数组转换为utf8然后手动删除空值的修复,这显然不是解决方案。)

public static void DecryptFileToFile(String fromFile, String toFile, byte[] Key)
{
    byte[] encryptedFile = IO.convertFileToByte(fromFile);

    using (Aes aesAlg = Aes.Create())
    {
        byte[] dataIV = encryptedFile.Take(16).ToArray(); //first 16 bytes is iv
        byte[] encryptedData = encryptedFile.Skip(16).Take(encryptedFile.Length-16).ToArray();
        aesAlg.Key = Key;
        using (var decryptor = aesAlg.CreateDecryptor(Key, dataIV))
        {
            byte[] final =  PerformCryptography(decryptor, encryptedData);
            string result = System.Text.Encoding.UTF8.GetString(final);
            result = result.Replace("\0", string.Empty);
            IO.writeStringToFile(result,toFile);
        }
    }
}
private static byte[] PerformCryptography(ICryptoTransform cryptoTransform, byte[] data)
{
    using (var memoryStream = new MemoryStream())
    {
        using (var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
        {
            cryptoStream.Write(data, 0, data.Length);
            cryptoStream.FlushFinalBlock();
            return memoryStream.ToArray();
        }
    }
}

加密:

public static void EncryptFileToFile(String fromFile, String toFile, byte[] Key){

            byte[] original = IO.convertFileToByte(fromFile);

            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.GenerateIV();
                aesAlg.Key = Key;
                using (var encryptor = aesAlg.CreateEncryptor(Key, aesAlg.IV))
                {
                    byte[] encryptedData =  PerformCryptography(encryptor, original);
                    byte[] final = Combine(aesAlg.IV,encryptedData);
                    IO.writeByteToFile(final, toFile);
                }

            }
        }

0 个答案:

没有答案