簡體   English   中英

無法解析壓縮、加密、解密、解壓stream實現

[英]Unable to resolve compression, encryption, decryption, decompression stream implementation

我一直在與鏈式 using 語句作斗爭,並且無法解決一長串實施問題中的最新問題。 我需要壓縮,然后加密和 append 生成的 IV 到所選文件。 這一切似乎都正常工作,但是我無法解除這個過程。 在查看了幾個類似的堆棧帖子和文章后,我仍然無法讓它工作,現在正在尋求更直接的幫助。

最新拋出的錯誤是System.IO.InvalidDataException: 'Found invalid data while decoding.' 看來解密 stream 沒有按預期運行,這使解壓縮 stream 變得異常。

byte[] key;
byte[] salt;
const int keySize = 256;
const int blockSize = keySize;
byte[] iv = new byte[blockSize / 8];//size to bits
RijndaelManaged rjndl;
RNGCryptoServiceProvider cRng;

void InitializeCryptor() {
    //Temporarily define the salt & key
    salt = Encoding.UTF8.GetBytes("SaltShouldBeAtLeast8Bytes");
    key = new Rfc2898DeriveBytes("MyL0ngPa$$phra$e", salt, 4).GetBytes(keySize / 8);

    //Initialize the crypto RNG generator
    cRng = new RNGCryptoServiceProvider();

    // Create instance of Rijndael (AES) for symetric encryption of the data.
    rjndl = new RijndaelManaged();
    rjndl.KeySize = keySize;
    rjndl.BlockSize = blockSize;
    rjndl.Mode = CipherMode.CBC;
}

void CompressAndEncryptFile(string relativeFilePath, string fileName) {
    //Create a unique IV each time
    cRng.GetBytes(iv);

    //Create encryptor
    rjndl.Key = key;
    rjndl.IV = iv;
    ICryptoTransform encryptor = rjndl.CreateEncryptor(rjndl.Key, rjndl.IV);

    //Create file specific output sub-directory
    Directory.CreateDirectory(Path.Combine(outputPath, relativeFilePath));

    //Read and compress file into memory stream
    using (FileStream readStream = File.OpenRead(Path.Combine(initialpath, relativeFilePath, fileName)))
            using (FileStream writeStream = new FileStream(Path.Combine(outputPath, relativeFilePath, fileName + ".dat"), FileMode.Create))
    using (CryptoStream encryptStream = new CryptoStream(writeStream, encryptor, CryptoStreamMode.Write))
    using (DeflateStream compStream = new DeflateStream(encryptStream, CompressionLevel.Optimal)) {
        //Write the following to the FileStream for the encrypted file:
        // - length of the IV
        // - the IV
        byte[] ivSize = BitConverter.GetBytes(rjndl.IV.Length);
        writeStream.Write(ivSize, 0, 4);
        writeStream.Write(rjndl.IV, 0, rjndl.BlockSize / 8);

        readStream.CopyTo(compStream);
    }
}

void DecryptAndDecompressFile(string relativeFilePath) {
    string outputPath = Path.Combine(initialpath, "Unpack");
    Directory.CreateDirectory(outputPath);

    using (FileStream readStream = new FileStream(Path.Combine(initialpath, manifestData.version, relativeFilePath + ".dat"), FileMode.Open)) {
        byte[] tmpLength = new byte[4];

        //Read length of IV
        readStream.Seek(0, SeekOrigin.Begin);
        readStream.Read(tmpLength, 0, 3);

        int ivLength = BitConverter.ToInt32(tmpLength, 0);

        byte[] readIv = new byte[ivLength];

        //Read IV
        readStream.Seek(4, SeekOrigin.Begin);
        readStream.Read(readIv, 0, ivLength);
        rjndl.IV = readIv;

        //Start at beginning of encrypted data
        readStream.Seek(4 + ivLength, SeekOrigin.Begin);

        //Create decryptor
        ICryptoTransform decryptor = rjndl.CreateEncryptor(key, readIv);
        using (CryptoStream decryptStream = new CryptoStream(readStream, decryptor, CryptoStreamMode.Read))
        using (DeflateStream decompStream = new DeflateStream(decryptStream, CompressionMode.Decompress))
        using (FileStream writeStream = new FileStream(Path.Combine(outputPath, relativeFilePath), FileMode.Create)) {
            decompStream.CopyTo(writeStream);
        }
    }
}

對於那些喜歡指出其他類似堆棧問題並在不提供支持的情況下投票關閉/復制的人,以下是我首先處理的線程和帖子,每個都沒有成功。 https: //docs.microsoft.com/en-us/dotnet/standard/security/walkthrough-creating-a-cryptographic-application https: //docs.microsoft.com/en-us/dotnet/api/system.security .cryptography.rijndaelmanaged?redirectedfrom=MSDN&view=netcore-3.1 鏈接 GZipStream/DeflateStream 和 CryptoStream (AES) 在讀取DeflateStream/GZipStream 到 CryptoStream 時中斷,反之亦然https://docs.microsoft.com/en-us/dotnet/api/ system.io.compression.gzipstream?redirectedfrom=MSDN&view=netcore-3.1#code-snippet-2 如何修復“解碼時發現無效數據”。 使用 C# 的壓縮/解壓字符串

經過大約 2 天的調查,我找到了我的錯誤。

我在解密部分調用rjndl.CreateEncryptor而不是rjndl.CreateDecryptor ......(請告訴我這種類型的 $#!t 也發生在其他人身上)

一旦我完成測試,我將更新我的問題代碼,以作為未來通過谷歌登陸這里的任何人的一個很好的例子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM