Exemplo n.º 1
0
        public static TrrntZipStatus ReZipFiles(List <ZippedFile> zippedFiles, ICompress originalZipFile, byte[] buffer, StatusCallback StatusCallBack, LogCallback LogCallback, int ThreadID)
        {
            int bufferSize = buffer.Length;

            string filename    = originalZipFile.ZipFilename;
            string tmpFilename = Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".tmp";

            string outfilename = Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".zip";

            if (Path.GetExtension(filename) == ".7z")
            {
                if (File.Exists(outfilename))
                {
                    LogCallback?.Invoke(ThreadID, "Error output .zip file already exists");
                    return(TrrntZipStatus.RepeatFilesFound);
                }
            }

            if (IO.File.Exists(tmpFilename))
            {
                IO.File.Delete(tmpFilename);
            }

            ICompress zipFileOut = new ZipFile();

            try
            {
                zipFileOut.ZipFileCreate(tmpFilename);

                // by now the zippedFiles have been sorted so just loop over them
                for (int i = 0; i < zippedFiles.Count; i++)
                {
                    StatusCallBack?.Invoke(ThreadID, (int)((double)(i + 1) / (zippedFiles.Count) * 100));

                    ZippedFile t = zippedFiles[i];

                    if (Program.VerboseLogging)
                    {
                        LogCallback?.Invoke(ThreadID, $"{t.Size,15}  {t.StringCRC}   {t.Name}");
                    }

                    Stream readStream = null;
                    ulong  streamSize = 0;
                    ushort compMethod;

                    ZipFile   z       = originalZipFile as ZipFile;
                    ZipReturn zrInput = ZipReturn.ZipUntested;
                    if (z != null)
                    {
                        zrInput = z.ZipFileOpenReadStream(t.Index, false, out readStream, out streamSize, out compMethod);
                    }
                    SevenZ z7 = originalZipFile as SevenZ;
                    if (z7 != null)
                    {
                        zrInput = z7.ZipFileOpenReadStream(t.Index, out readStream, out streamSize);
                    }

                    Stream    writeStream;
                    ZipReturn zrOutput = zipFileOut.ZipFileOpenWriteStream(false, true, t.Name, streamSize, 8, out writeStream);

                    if (zrInput != ZipReturn.ZipGood || zrOutput != ZipReturn.ZipGood)
                    {
                        //Error writing local File.
                        zipFileOut.ZipFileClose();
                        originalZipFile.ZipFileClose();
                        IO.File.Delete(tmpFilename);
                        return(TrrntZipStatus.CorruptZip);
                    }

                    Stream crcCs = new CrcCalculatorStream(readStream, true);

                    ulong sizetogo = streamSize;
                    while (sizetogo > 0)
                    {
                        int sizenow = sizetogo > (ulong)bufferSize ? bufferSize : (int)sizetogo;

                        crcCs.Read(buffer, 0, sizenow);
                        writeStream.Write(buffer, 0, sizenow);
                        sizetogo = sizetogo - (ulong)sizenow;
                    }
                    writeStream.Flush();

                    crcCs.Close();
                    if (z != null)
                    {
                        originalZipFile.ZipFileCloseReadStream();
                    }

                    uint crc = (uint)((CrcCalculatorStream)crcCs).Crc;

                    if (crc != t.CRC)
                    {
                        return(TrrntZipStatus.CorruptZip);
                    }

                    zipFileOut.ZipFileCloseWriteStream(t.ByteCRC);
                }

                zipFileOut.ZipFileClose();
                originalZipFile.ZipFileClose();
                IO.File.Delete(filename);
                IO.File.Move(tmpFilename, outfilename);

                return(TrrntZipStatus.ValidTrrntzip);
            }
            catch (Exception)
            {
                zipFileOut?.ZipFileCloseFailed();
                originalZipFile?.ZipFileClose();
                return(TrrntZipStatus.CorruptZip);
            }
        }
Exemplo n.º 2
0
        public static TrrntZipStatus ReZipFiles(List <ZippedFile> zippedFiles, ICompress originalZipFile, byte[] buffer, StatusCallback statusCallBack, LogCallback logCallback, int threadId)
        {
            zipType inputType;

            switch (originalZipFile)
            {
            case Zip _:
                inputType = zipType.zip;
                break;

            case SevenZ _:
                inputType = zipType.sevenzip;
                break;

            case Compress.File.File _:
                inputType = zipType.iso;
                break;

            default:
                return(TrrntZipStatus.Unknown);
            }

            zipType outputType = Program.OutZip == zipType.both ? inputType : Program.OutZip;

            if (outputType == zipType.iso)
            {
                outputType = zipType.zip;
            }

            int bufferSize = buffer.Length;

            string filename    = originalZipFile.ZipFilename;
            string tmpFilename = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename) + ".tmp");

            string outExt      = outputType == zipType.zip ? ".zip" : ".7z";
            string outfilename = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename) + outExt);

            if (inputType != outputType)
            {
                if (File.Exists(outfilename))
                {
                    logCallback?.Invoke(threadId, "Error output " + outExt + " file already exists");
                    return(TrrntZipStatus.RepeatFilesFound);
                }
            }

            if (File.Exists(tmpFilename))
            {
                File.Delete(tmpFilename);
            }

            ICompress zipFileOut = outputType == zipType.zip ? new Zip() : (ICompress) new SevenZ();

            try
            {
                zipFileOut.ZipFileCreate(tmpFilename);


                ulong fileSizeTotal       = 0;
                ulong fileSizeProgress    = 0;
                int   filePercentReported = 20;
                foreach (ZippedFile f in zippedFiles)
                {
                    fileSizeTotal += f.Size;
                }

                // by now the zippedFiles have been sorted so just loop over them
                foreach (ZippedFile t in zippedFiles)
                {
                    if (Program.VerboseLogging)
                    {
                        logCallback?.Invoke(threadId, $"{t.Size,15}  {t.StringCRC}   {t.Name}");
                    }

                    Stream readStream = null;
                    ulong  streamSize = 0;

                    ZipReturn zrInput = ZipReturn.ZipUntested;
                    switch (originalZipFile)
                    {
                    case Zip z:
                        zrInput = z.ZipFileOpenReadStream(t.Index, false, out readStream, out streamSize, out ushort _);
                        break;

                    case SevenZ z7:
                        zrInput = z7.ZipFileOpenReadStream(t.Index, out readStream, out streamSize);
                        break;

                    case Compress.File.File zf:
                        zrInput = zf.ZipFileOpenReadStream(t.Index, out readStream, out streamSize);
                        break;
                    }


                    ZipReturn zrOutput = zipFileOut.ZipFileOpenWriteStream(false, true, t.Name, streamSize, 8, out Stream writeStream);

                    if ((zrInput != ZipReturn.ZipGood) || (zrOutput != ZipReturn.ZipGood))
                    {
                        //Error writing local File.
                        zipFileOut.ZipFileClose();
                        originalZipFile.ZipFileClose();
                        File.Delete(tmpFilename);
                        return(TrrntZipStatus.CorruptZip);
                    }

                    Stream crcCs = new CrcCalculatorStream(readStream, true);

                    ulong sizetogo = streamSize;
                    while (sizetogo > 0)
                    {
                        int sizenow = sizetogo > (ulong)bufferSize ? bufferSize : (int)sizetogo;

                        fileSizeProgress += (ulong)sizenow;
                        int filePercent = (int)((double)fileSizeProgress / fileSizeTotal * 20);
                        if (filePercent != filePercentReported)
                        {
                            statusCallBack?.Invoke(threadId, filePercent * 5);
                            filePercentReported = filePercent;
                        }

                        crcCs.Read(buffer, 0, sizenow);
                        writeStream.Write(buffer, 0, sizenow);
                        sizetogo = sizetogo - (ulong)sizenow;
                    }
                    writeStream.Flush();

                    crcCs.Close();
                    if (inputType != zipType.sevenzip)
                    {
                        originalZipFile.ZipFileCloseReadStream();
                    }

                    uint crc = (uint)((CrcCalculatorStream)crcCs).Crc;

                    if (t.CRC == null)
                    {
                        t.CRC = crc;
                    }

                    if (crc != t.CRC)
                    {
                        return(TrrntZipStatus.CorruptZip);
                    }

                    zipFileOut.ZipFileCloseWriteStream(t.ByteCRC);
                }
                statusCallBack?.Invoke(threadId, 100);

                zipFileOut.ZipFileClose();
                originalZipFile.ZipFileClose();
                File.Delete(filename);
                File.Move(tmpFilename, outfilename);

                return(TrrntZipStatus.ValidTrrntzip);
            }
            catch (Exception)
            {
                zipFileOut?.ZipFileCloseFailed();
                originalZipFile?.ZipFileClose();
                return(TrrntZipStatus.CorruptZip);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 将文件利用AES进行静态解密
        /// </summary>
        /// <param name="inputFile">输入的文件路径</param>
        /// <param name="outputFile">输出的文件路径</param>
        /// <param name="aesKey">AES密钥</param>
        /// <param name="aesIV">AES初始向量</param>
        public static void DecryptFile(string inputFile, string outputFile, byte[] aesKey, byte[] aesIV, StatusCallback callback = null)
        {
            if (string.IsNullOrEmpty(inputFile))
            {
                throw new ArgumentNullException("inputFile");
            }
            if (string.IsNullOrEmpty(outputFile))
            {
                throw new ArgumentNullException("outputFile");
            }
            if (!File.Exists(inputFile))
            {
                throw new ArgumentException("inputFile not exists");
            }
            if (aesKey == null)
            {
                throw new ArgumentNullException("aesKey");
            }
            if (aesIV == null)
            {
                throw new ArgumentNullException("aesIV");
            }
            FileStream fs_in = null, fs_out = null;

            try
            {
                fs_in  = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                fs_out = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None);
                var file_length      = fs_in.Length;
                var proceeded_length = 3;

                int type = fs_in.ReadByte();
                if (type != FLG_STATIC_KEY)
                {
                    fs_in.Close();
                    fs_out.Close();
                    throw new InvalidDataException("格式错误:该文件不是采用静态加密的文件");
                }
                var preserved = util.ReadBytes(fs_in, 2); //preserved for latter usage

                var       decrypted_stream = Crypto.AES_StreamDecrypt(fs_in, aesKey, CipherMode.CFB, aesIV);
                int       nread            = 0;
                const int buffer_size      = 4096;
                var       buffer           = new byte[buffer_size];
                var       sha1             = new SHA1CryptoServiceProvider();
                byte[]    SHA1             = util.ReadBytes(decrypted_stream, 20);
                do
                {
                    nread             = decrypted_stream.Read(buffer, 0, buffer_size);
                    proceeded_length += nread;
                    fs_out.Write(buffer, 0, nread);
                    sha1.TransformBlock(buffer, 0, nread, buffer, 0);
                    callback?.Invoke(inputFile, outputFile, proceeded_length, file_length);
                } while (nread != 0);
                sha1.TransformFinalBlock(buffer, 0, 0);
                var cur_sha1 = sha1.Hash;
                fs_out.Close();
                decrypted_stream.Close();
                var sha1_empty = new byte[20];
                if (util.Hex(cur_sha1) != util.Hex(SHA1) && util.Hex(SHA1) != util.Hex(sha1_empty))
                {
                    throw new InvalidDataException("SHA1检验不匹配:解密失败");
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                fs_in?.Close();
                fs_out?.Close();
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// 将文件利用RSA+AES进行动态加密
        /// </summary>
        /// <param name="inputFile">输入的文件路径</param>
        /// <param name="outputFile">输出的文件路径</param>
        /// <param name="rsaPublic">RSA公钥</param>
        /// <param name="SHA1">文件的SHA1值(可选,用于解密的校验)</param>
        public static void EncryptFile(string inputFile, string outputFile, byte[] rsaPublic, string SHA1 = null, StatusCallback callback = null)
        {
            if (rsaPublic == null)
            {
                throw new ArgumentNullException("rsaPublic");
            }
            if (string.IsNullOrEmpty(inputFile))
            {
                throw new ArgumentNullException("inputFile");
            }
            if (string.IsNullOrEmpty(outputFile))
            {
                throw new ArgumentNullException("outputFile");
            }
            if (!File.Exists(inputFile))
            {
                throw new ArgumentException("inputFile not exists");
            }
            FileStream fs_in = null, fs_out = null;

            try
            {
                fs_in  = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                fs_out = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None);
                var  file_length      = fs_in.Length;
                long proceeded_length = 0;

                var rsa = new RSACryptoServiceProvider();
                rsa.ImportCspBlob(rsaPublic);
                byte[] sha1_value = rsa.Encrypt(new byte[20], false);
                if (!string.IsNullOrEmpty(SHA1))
                {
                    sha1_value = rsa.Encrypt(util.Hex(SHA1), false);
                }
                var rnd    = new Random();
                var aesKey = new byte[32];
                rnd.NextBytes(aesKey);
                var aesIV = new byte[16];
                rnd.NextBytes(aesIV);
                var aes_key_value = rsa.Encrypt(aesKey, false);
                var aes_iv_value  = rsa.Encrypt(aesIV, false);

                fs_out.WriteByte(FLG_DYNAMIC_KEY);
                fs_out.Write(sha1_value, 0, sha1_value.Length);
                fs_out.Write(aes_key_value, 0, aes_key_value.Length);
                fs_out.Write(aes_iv_value, 0, aes_iv_value.Length);
                fs_out.Write(new byte[2], 0, 2); //preserved for latter usage

                fs_out.Flush();
                var       encrypted_stream = Crypto.AES_StreamEncrypt(fs_out, aesKey, CipherMode.CFB, aesIV);
                int       nread            = 0;
                const int buffer_size      = 4096;
                var       buffer           = new byte[buffer_size];
                do
                {
                    nread = fs_in.Read(buffer, 0, buffer_size);
                    encrypted_stream.Write(buffer, 0, nread);
                    proceeded_length += nread;
                    callback?.Invoke(inputFile, outputFile, proceeded_length, file_length);
                } while (nread != 0);
                encrypted_stream.FlushFinalBlock();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                fs_in?.Close();
                fs_out?.Close();
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// 将文件利用AES进行静态加密
        /// </summary>
        /// <param name="inputFile">输入的文件路径</param>
        /// <param name="outputFile">输出的文件路径</param>
        /// <param name="aesKey">AES密钥</param>
        /// <param name="aesIV">AES初始向量</param>
        /// <param name="SHA1">文件的SHA1值</param>
        public static void EncryptFile(string inputFile, string outputFile, byte[] aesKey, byte[] aesIV, string SHA1 = null, StatusCallback callback = null)
        {
            if (string.IsNullOrEmpty(inputFile))
            {
                throw new ArgumentNullException("inputFile");
            }
            if (string.IsNullOrEmpty(outputFile))
            {
                throw new ArgumentNullException("outputFile");
            }
            if (!File.Exists(inputFile))
            {
                throw new ArgumentException("inputFile not exists");
            }
            FileStream fs_in = null, fs_out = null;

            try
            {
                fs_in  = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                fs_out = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None);
                var file_length      = fs_in.Length;
                var proceeded_length = 0;

                if (aesKey == null)
                {
                    throw new ArgumentNullException("aesKey");
                }
                if (aesIV == null)
                {
                    throw new ArgumentNullException("aesIV");
                }
                if (!string.IsNullOrEmpty(SHA1) && SHA1.Length != 40)
                {
                    throw new ArgumentException("Invalid SHA1 Checksum");
                }

                fs_out.WriteByte(FLG_STATIC_KEY);
                fs_out.Write(new byte[2], 0, 2); //preserved for latter usage
                fs_out.Flush();

                var encrypted_stream = Crypto.AES_StreamEncrypt(fs_out, aesKey, CipherMode.CFB, aesIV);
                var sha1_value       = new byte[20];
                if (!string.IsNullOrEmpty(SHA1))
                {
                    sha1_value = util.Hex(SHA1);
                }
                encrypted_stream.Write(sha1_value, 0, 20);

                int       nread       = 0;
                const int buffer_size = 4096;
                var       buffer      = new byte[buffer_size];
                do
                {
                    nread             = fs_in.Read(buffer, 0, buffer_size);
                    proceeded_length += nread;
                    encrypted_stream.Write(buffer, 0, nread);
                    callback?.Invoke(inputFile, outputFile, proceeded_length, file_length);
                } while (nread != 0);
                encrypted_stream.FlushFinalBlock();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                fs_in?.Close();
                fs_out?.Close();
            }
        }
Exemplo n.º 6
0
 private void TzStatusCallBack(int processId, int percent)
 {
     StatusCallBack?.Invoke(processId, percent);
 }