You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解密并解压还原文本?C#加密压缩后还原失败求助

解决加密压缩文本还原失败的问题

嘿,我看你在解密还原加密压缩文本的时候卡壳了——这种问题大多出在加密解密流程不匹配或者流处理细节没做好上!先给你梳理几个最容易踩的坑,再给你一套能跑通的完整代码参考:

常见错误点

  • 密钥/IV不匹配:解密时用的密钥或初始化向量(IV)和加密时不一致,这是最常见的原因(IV可以和加密数据一起存储,不需要保密)
  • 流的顺序搞反了:加密时是「压缩文本 → 加密压缩后的数据」,解密必须反过来「解密数据 → 解压解密后的内容」,顺序错了直接读不出有效数据
  • 流未正确释放:没有用using语句或手动关闭流,导致部分数据没写入/读取完整
  • 编码不一致:加密前用UTF-8转字节,解密后用其他编码转回文本,导致乱码或内容缺失

修正后的完整代码

using System;
using System.IO;
using System.Text;
using System.IO.Compression;
using System.Security.Cryptography;

static class Program
{
    // 这里可以替换成你自己的密钥(建议32字节=256位,对应AES-256)
    private static readonly byte[] EncryptionKey = Encoding.UTF8.GetBytes("your-32-character-secret-key-here");

    static void Main()
    {
        string originalText = "这里是你要压缩加密的大文本内容,随便写多少都可以!";
        string encryptedFilePath = "encrypted_data.bin";
        string decryptedTextPath = "decrypted_text.txt";

        // 第一步:加密压缩并保存
        EncryptAndCompressText(originalText, encryptedFilePath);
        Console.WriteLine("加密压缩文件已生成:" + encryptedFilePath);

        // 第二步:解密解压并还原文本
        string decryptedText = DecryptAndDecompressText(encryptedFilePath);
        File.WriteAllText(decryptedTextPath, decryptedText, Encoding.UTF8);
        Console.WriteLine("文本已还原到:" + decryptedTextPath);
        Console.WriteLine("还原内容:\n" + decryptedText);
    }

    /// <summary>
    /// 把文本压缩后加密,保存到文件
    /// </summary>
    static void EncryptAndCompressText(string text, string outputFilePath)
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = EncryptionKey;
            // 生成随机IV,和加密数据一起存(IV不需要保密)
            aes.GenerateIV();

            using (FileStream fs = new FileStream(outputFilePath, FileMode.Create))
            {
                // 先把IV写入文件开头,解密时要用到
                fs.Write(aes.IV, 0, aes.IV.Length);

                // 流顺序:FileStream → CryptoStream(加密)→ GZipStream(压缩)
                using (CryptoStream cs = new CryptoStream(fs, aes.CreateEncryptor(), CryptoStreamMode.Write))
                using (GZipStream gzs = new GZipStream(cs, CompressionMode.Compress))
                using (StreamWriter sw = new StreamWriter(gzs, Encoding.UTF8))
                {
                    sw.Write(text);
                }
            }
        }
    }

    /// <summary>
    /// 从加密文件中解密并解压,还原文本
    /// </summary>
    static string DecryptAndDecompressText(string inputFilePath)
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = EncryptionKey;

            using (FileStream fs = new FileStream(inputFilePath, FileMode.Open))
            {
                // 先读取文件开头的IV(AES的IV固定是16字节)
                byte[] iv = new byte[aes.IV.Length];
                fs.Read(iv, 0, iv.Length);
                aes.IV = iv;

                // 流顺序:FileStream → CryptoStream(解密)→ GZipStream(解压)
                using (CryptoStream cs = new CryptoStream(fs, aes.CreateDecryptor(), CryptoStreamMode.Read))
                using (GZipStream gzs = new GZipStream(cs, CompressionMode.Decompress))
                using (StreamReader sr = new StreamReader(gzs, Encoding.UTF8))
                {
                    return sr.ReadToEnd();
                }
            }
        }
    }
}

关键细节说明

  1. IV的处理:加密时生成随机IV并写入文件开头,解密时先读取IV再初始化AES,保证解密和加密的IV一致
  2. 流的嵌套顺序:加密是「写文本→压缩→加密→存文件」,解密是「读文件→解密→解压→读文本」,严格对应
  3. using语句的使用:所有流都用using自动释放资源,避免数据残留或资源泄漏
  4. 统一编码:全程用UTF-8处理文本,避免编码不一致导致的乱码

你可以对比下自己的代码,看看是不是在上面某一步出了问题——比如有没有正确保存/读取IV,流的顺序是不是反了,或者有没有漏写using导致流没正确关闭。

内容的提问来源于stack exchange,提问作者Andrey Bushman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:22:24